Convert map <Integer, List <Integer> to list <Integer> using java8 streams

I liked the concept of Streams in java 8. Now I want to convert a map in java to a sorted list using Java streams. I just want to display the list without saving it anywhere. I want to get this result in the resulting list:

5, 7, 8, 10, 19, 20, 22, 28, 30, 35, 40, 45, 50 . 

Here is my code:

    Map<Integer, List<Integer>> obj=new HashMap<Integer, List<Integer>>();
    obj.put(5, Arrays.asList(7,8,30));
    obj.put(10, Arrays.asList(20));
    obj.put(19, Arrays.asList(22,50));
    obj.put(28, Arrays.asList(35,40,45));
+4
source share
1 answer

I don’t understand why someone would want to do this (other than playing with Streams), but you can convert Mapto flat Streamout Integer, and then sort it:

List<Integer> sorted =
    obj.entrySet()
       .stream()
       .flatMap(e-> Stream.concat(Stream.of(e.getKey()),e.getValue().stream()))
       .sorted()
       .collect(Collectors.toList());
+10
source

Source: https://habr.com/ru/post/1675241/


All Articles