Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<Integer, List<Integer>> to List<Integer> using java8 streams

I liked Streams concept in java 8 . Now I want to convert a Map in java to a sorted List with the help of Java Streams. I just want to display the list without storing it anywhere. I want this output in resulting list:

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

Here's 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));
like image 675
raj Avatar asked Dec 24 '22 18:12

raj


1 Answers

I don't see why anyone would want to do that (except for playing with Streams), but you can convert the Map to a flat Stream of Integers 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());
like image 53
Eran Avatar answered Jan 03 '23 11:01

Eran