HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

Convert Set to List without creating new List

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
creatingsetconvertlistwithoutnew

Problem

I am using this code to convert a Set to a List:

Map> mainMap = new HashMap<>();

for (int i=0; i  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?

Solution

You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.

List mainList = new ArrayList();
mainList.addAll(set);


EDIT: as respond to the edit of the question.

It is easy to see that if you want to have a Map with Lists 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 a Map or Map instead, and just insert your set.

Code Snippets

List<String> mainList = new ArrayList<String>();
mainList.addAll(set);

Context

Stack Overflow Q#8892360, score: 925

Revisions (0)

No revisions yet.