I am using this code to convert a Set
to a List
:
Map<String, List<String>> mainMap = new HashMap<>(); for (int i=0; i < something.size(); i++) { Set<String> set = getSet(...); //returns different result each time List<String> 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?
The most straightforward way to convert a set to a list is by passing the set as an argument while creating the list. This calls the constructor and from there onwards the constructor takes care of the rest. Since the set has been converted to a list, the elements are now ordered.
We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.
The simplest way to convert list to set in Python is by using the set() function. The set() method is used to convert an iterable element such as a list, dictionary, or tuple into the set.
You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.
List<String> mainList = new ArrayList<String>(); 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 List
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 a Map<String,Set>
or Map<String,Collection>
instead, and just insert your set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With