Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

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 this possible?

1 Answer

0 votes
by (3.5k points)

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

List<String> mainList = new ArrayList<String>();

mainList.addAll(set);

It is simple to see that if you want to beget a Map with Lists as values, to produce k distinct values, you need to generate k different lists. 

Thus: You cannot bypass creating these lists at all, the lists will be created.

Feasible workaround: 

Set your Map as a 

Map<String,Set> or Map<String,Collection> alternatively, and just enter your set.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Oct 3, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...