'How do I create a List<Map.Entry<String, Integer>> out of a Map<String, Integer>?
So I know how to create a List of Map values
new ArrayList<String, Integer>(map.getValues());
Or from entry set map.entrySet()
However there doesn't seem to be a similar way to add a list of Map.Entry<String, Integer>
Is there a way to do this so I can write it all in just a return statement?
Map<String, Integer> map = new TreeMap<String, Integer>();
public List<Map.Entry<String, Integer>> getWordList(){
return new ArrayList<Map.Entry<String, Integer>>(map);
}
This doesn't work. But what does?
Solution 1:[1]
entrySet returns a Set and not a List, which means that the map's keys may or may not be in order.
However, in the case of TreeMap the JavaDoc says the following about it:
Returns a
Setview of the mappings contained in this map.The set's iterator returns the entries in ascending key order.
Apparently, entrySet() guarantees the mappings to be in the same order as the TreeMap. In short, you could just use it anywhere where a Collection is required. Creating a List is then trivial:
new ArrayList<>(map.entrySet())
or
List.copyOf(map.entrySet())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
