Łukasz Senderowski
Łukasz Senderowski

Reputation: 23

passing lambda as method arg and sorting map


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

Upvotes: 2

Views: 737

Answers (3)

Robin Topper
Robin Topper

Reputation: 2344

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

Upvotes: 2

holi-java
holi-java

Reputation: 30696

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 ...;
}

Upvotes: -1

Eugene
Eugene

Reputation: 120968

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

Upvotes: 3

Related Questions