Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of singletonList?

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.

like image 877
mmoore Avatar asked Jun 26 '12 10:06

mmoore


1 Answers

To answer your actual question :

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?

The typical use is if you have one element and want to pass it to a method that accepts a List, ie

public void registerUsers(List<User> users) {...}

User currentUser = Login Manager.getCurrentUser();
registerUsers(Collections.singletonList(currentUser));

The removeAll() is a special case for this.

like image 186
daniu Avatar answered Nov 02 '22 15:11

daniu