I am using this code to convert a Set
to a List
:
Map<String, List> mainMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
Set set = getSet(...); //returns different result each time
List listOfNames = new ArrayList(set);
mainMap.put(differentKeyName,listOfNames);
}
I want to avoid creating a new list in each iteration of the loop. Is that possible?
Java 8 provides the option of using streams and you can get a list from
Set<String> setString
as:Though the internal implementation as of now provides an instance of
ArrayList
:but JDK does not guarantee it. As mentioned here:
In case you want to be sure always then you can request for an instance specifically as:
I create simple
static
method:... or if you want to set type of List you can use:
You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.
EDIT: as respond to the edit of the question.
It is easy to see that if you want to have a
Map
withList
s as values, in order to have k different values, you need to create k different lists.Thus: You cannot avoid creating these lists at all, the lists will have to be created.
Possible work around:
Declare your
Map
as aMap<String,Set>
orMap<String,Collection>
instead, and just insert your set.We can use following one liner in Java 8:
Here is one small example:
You could use this one line change:
Arrays.asList(set.toArray(new Object[set.size()]))