0

I have a map with key as string and value as list of strings

I want to sort the map based on the list of strings(Lexicographically).

If I have a List<List<String>> then I can sort by

List<List<String>> sortedlist = new LinkedList<>();
sortedlist.sort((l1, l2) -> l1.get(0).compareTo(l2.get(0)));

But I have a Map<String, List<String>> sortedMap and I want to sort this based on the values, i.e. first element of each list within the value set of the map.

I am trying to form a stream lambda expression something like this.

HashMap<String, List<String> > sortedmap = new HashMap<>();
sortedmap = map.values().stream().sorted(Map.Entry.comparingByValue((l1, l2) -> l1.get(0).compareTo(l2.get(0))) )

But it is not a valid lambda expression.

How do I do this with Java 8 streams?

Naman
  • 27,789
  • 26
  • 218
  • 353

1 Answers1

2

Try this:

Map<String, List<String>> sortedMap = 
    map.entrySet() 
       .stream()
       .sorted(Map.Entry.comparingByValue(Comparator.comparing(l -> l.get(0))))
       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));

Note that sorting would not make any sense while collecting into a HashMap, since it's unordered.

ETO
  • 6,970
  • 1
  • 20
  • 37