I was looking around for some elegant solution to removing null values from a List. I came across the following post, which says I can use list.removeAll(Collections.singletonList(null));
This, however, throws an UnsupportedOperationException, which I’m assuming is because removeAll() is attempting to do some mutative operation on the immutable singleton collection. Is this correct?
If this is the case, what would be a typical use of this singletonList? To represent a collection of size 1 when you’re sure you don’t want to actually do anything with the collection?
Thanks in advance.
It works like a charm:
Indeed
Collections.singletonList(null)is immutable (which is unfortunately hidden in Java[1]), but the exception is thrown from yourlistvariable. Apparently it is immutable as well, like in example below:This code will throw an
UnsupportedOperationException. So as you can seesingletonList()is useful in this case. Use it when client code expects a read-only list (it won’t modify it) but you only want to pass one element in it.singletonList()is (thread-)safe (due to immutability), fast and compact.[1] E.g. in scala there is a separete hierarchy for mutable and immutable collections and API can choose whether it accept this or the other (or both, as they have common base interfaces)