I want to convert Map
to List
with each map entry - to 1 entry in the list as \"key - value\"
I search
if you want just the values of the Map try this
List<String> list = new ArrayList<>(map.values())
{"apple", "orange"}
List<String> list = map.entrySet()
.stream()
.map(entry -> entry.getKey() + "-" + entry.getValue())
.sorted()
.collect(Collectors.toList());
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());
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());