问题
I want to convert Map<Integer, String>
to List<String>
with each map entry - to 1 entry in the list as "key - value"
I searched and I only found to map values only to List.
Map<Integer, String> map = new HashMap<>();
map.put(10, "apple");
map.put(20, "orange");
map.put(30, "banana");
map.put(40, "watermelon");
map.put(50, "dragonfruit");
I want this to be mapped to list as
"10-apple"
"20-orange"
and so on.
this can be done easily if I used foreach .. but I want to know if it is feasible to get it through streams
回答1:
List<String> list = map.entrySet()
.stream()
.map(entry -> entry.getKey() + "-" + entry.getValue())
.sorted()
.collect(Collectors.toList());
回答2:
Just a slightly different variant to the other answers. if the insertion/iteration order is important then I'd rather use a LinkedHashMap
in the first place as opposed to using a HashMap
then sorting it which is actually not always guaranteed to work.
Example:
Map<Integer, String> map = new LinkedHashMap<>();
...
...
...
then stream over the entrySet and collect to a list implementation:
List<String> list = map.entrySet()
.stream()
.map(e -> e.getKey() + "-" + e.getValue())
.collect(Collectors.toList());
回答3:
Here is one variant using .map to move from list to map
List<String> list = map.entrySet()
.stream()
.map(x -> String.format("%d-%s", x.getKey().intValue(), x.getValue()))
.sorted().collect(Collectors.toList());
来源:https://stackoverflow.com/questions/51341620/convert-map-to-liststring-as-key-value-to-each-list-entry