Reputation: 23
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
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
Reputation: 30696
Function declared 2 generic arguments: T and R, but you only given 1 generic parameter Set
.
collecting a stream to a Map you can using Collectors.toMap rather than Collectors.toList which is collecting a stream to a List.
Comparator is more like a BiFunction/ToIntBiFunction due to the number of generic arguments of a Functional Interface includes parameters & return type.
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
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