0

I have a map Map<K, List<V>> inputMap I want to sort list before storing to list

List<String> outputList = inputMap.keySet()
 .stream()
 .filter(Objects::nonNull)
 .map(key -> (key + "==" + inputMap.get(key).sort(c);))
 .sorted()
 .collect(Collectors.toList());
7
  • How is your comparator c implemented? Commented Apr 29, 2017 at 17:49
  • 1
    Post is not clear. Elaborate what are you trying to achieve Commented Apr 29, 2017 at 17:51
  • the most important, you must implements your comparator c correctly. and the code above even can't be compiled due to List.sort not return anything. Commented Apr 29, 2017 at 17:52
  • So you want to sort each List<V> and then join them into a bigger list? Commented Apr 29, 2017 at 17:53
  • @NickZiebert what he want is: {b:[4,3],null:[5,6], a:[2,1]} will output: ["a == [1, 2]", "b ==[3, 4]"] Commented Apr 29, 2017 at 17:55

1 Answer 1

3

How about this?

List<String> outputList = inputMap.keySet().stream()
            .filter(Objects::nonNull)
            .map(key -> key + "==" 
                            + inputMap.get(key).stream().sorted(c)
                                               .collect(Collectors.toList()))
            .sorted()
            .collect(Collectors.toList());

OR

List<String> outputList = inputMap.keySet().stream()
            .filter(Objects::nonNull)
            .map(key -> key + "=="
                            + inputMap.get(key).stream().sorted(c)
                                        .map(Object::toString)
                                        .collect(Collectors.joining(", ","[","]")))
            .sorted()
            .collect(Collectors.toList());    
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, second solution worked for me, but I changed my map to Map<K, List<String>>. but Can you help for generic type sorted(c) comparator part
@RiteshChouhan Hi, but I still remind you that the first solution can also work fine.
Yeah its working, I have verified that also, Thanks :)

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.