4

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));

1 Answer 1

10

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());
Sign up to request clarification or add additional context in comments.

1 Comment

I just wanted to find another way to flatten a linked list . geeksforgeeks.org/flattening-a-linked-list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.