2


i must create Sorted method, called with map arguments and lambda-expression. The method returns a sorted version of any map passed as the first argument, and the sort order is determined by the lambda expression, given as the second argument. i created something like that(dont work correctly):

public Map sorted(Map map, Function<Set> funct){


    System.out.println(map.entrySet()
       .stream()
       .sorted((Comparator) funct)
       .collect(Collectors.toList()));
     return null;
}

Any ideas ?
Thanks for help ;)

3
  • 3
    You are supposed to pass a Comparator<Map.Entry<KeyType,ValueType>> to the sorted method. Commented Apr 25, 2017 at 9:51
  • Function is different with Comparator Commented Apr 25, 2017 at 9:52
  • You "must"? Because it's much more readable to just Map<K,V> sorted = new TreeMap<>(comparator); sorted.putAll(map); return sorted; Commented Apr 25, 2017 at 10:37

3 Answers 3

3

If you want a sorted map that would be a TreeMap and assuming the comparator sorts by Key, it could look like this:

 public static <K, V> TreeMap<K, V> sorted(Map<K, V> map, Comparator<? super K> cmp) {

    return map.entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey,     
                          Map.Entry::getValue, 
                          (left, right) -> left, 
                          () -> new TreeMap<K, V>(cmp)));

}

And an invocation of it would look like this for example:

 System.out.println(sorted(map, Comparator.naturalOrder()));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for help, it was very usefull ;)
2

When I read the question I was thinking of a more general solution where you can sort the map on either keys or values. In that case the solution looks like this:

public static <K,V> Map<K,V> sorted(Map<K,V> map, Comparator<Map.Entry<K, V>> comparator){
    return map.entrySet()
       .stream()
       .sorted(comparator)
       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

If you want to want to sort by value, you can use this method like this:

sorted(yourMap, Entry.comparingByValue());

3 Comments

The usage example can be "shortened" as sorted(map, Comparator.comparing(Map.Entry::getValue)).
And even shorter with sorted(map, Entry.comparingByValue())
Live and learn, they say! :) Realistically, I'd use the appropriate usage directly in the answer, instead of showing a somewhat complicated construct.
-1

IF you want to refer a ToIntBiFunction to a Comparator you can use this:

void sortByEntry() {
    Map<?, ?> map = new HashMap<>();
    Map<?, ?> sorted = sorted(map, this::comparingEntry);
}

<K, V> Map<K, V> sorted(Map<K, V> map, 
                        ToIntBiFunction<Entry<K, V>, Entry<K, V>> comparator) {
    return map.entrySet().stream()
            .sorted(comparator::applyAsInt)
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue
                                    , (v1, v2) -> v2, LinkedHashMap::new));
}

<K, V> int comparingEntry(Entry<K, V> left, Entry<K, V> right) {
    return ...;
}

4 Comments

Comparator is a @FunctionalInterface. There is therefore no need to replace it with ToIntBiFunction. Doing so adds complexity where there is none. This is why I downvoted this answer. If we remove that ToIntBiFunction, the whole answer collapses and falls back on to @Eugene's or @RobinTopper' answer, making it a duplicate.
@OlivierGrégoire first, thanks for your comment. I know Comparator is a Functional Interface, but I want to tell how to alternative between Functional Interfaces to OP. and RobinTopper's answer is after mine.
The intent of your answer isn't really clear then. Would you mind edit your answer to make that more prominent? This way I can retract my downvote as well (since it's locked until further edit).
@OlivierGrégoire It doesn't matter, I don't matter the votes. but still thanks for your feedback again.

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.