Skip to content
Advertisement

Java 11: convert List to TreeMap<String, List> using Collectors

I have a list like that

JavaScript

I want to convert that List into a TreeMap<String, List<String>> like that:

JavaScript

My code so far:

JavaScript

I have two problems.

  1. First is that TreeMap::new is probably not working because the order is not the same as the original’s List.
  2. Second is that I don’t seem to find a way to make that List<String[]> into a List<String>.

Any ideas?

Advertisement

Answer

You want to use a LinkedHashMap to preserve original order. So your code should look like this:

JavaScript

If your keys are not unique, you can use the grouping collector with something like this (Collectors.flatMapping requires Java 9+):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement