问题
I am trying to sort elements by their frequency
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int itr = Integer.parseInt(br.readLine());
for (int i = 0; i < itr; i++) {
int n = Integer.parseInt(br.readLine());
String[] val = br.readLine().split(" ");
Map<Integer, Integer> map = new HashMap<>();
for (int j = 0; j < n; j++) {
Integer temp = Integer.parseInt(val[j]);
map.putIfAbsent(temp, 0);
map.put(temp, map.get(temp) + 1);
}
here I am sorting the map based on freq and storing it back as a linkedHashMap.
Map<Integer, Integer> sortedMap = map.entrySet().stream()
.sorted(
(Map.Entry.<Integer, Integer>comparingByValue())
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
for(Map.Entry entries : sortedMap.entrySet()){
System.out.println(entries.getKey() + " " + entries.getValue());
}
}
}
}
Below is throwing compiler error.
Map<Integer, Integer> sortedMap = map.entrySet().stream()
.sorted(
(Map.Entry.comparingByValue())
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Sample input 1 6 4 -2 10 12 -8 4
Sample Output 0
-8 -2 10 12 4 4
回答1:
public static <K, V extends Comparable<? super V>>
Comparator<Map.Entry<K, V>> comparingByValue()
is a static method and it requires K, V
to set/correct/adjust the generic context correctly when it's used within one. Otherwise, it assumes K
is Object
and V
is Comparable
which is not what Stream<Map.Entry<Integer, Integer>>#sorted
expects. Note that the stream got <Map.Entry<Integer, Integer>>
from either map.entrySet()
, where the map
is parametrised by <Integer, Integer>
or the type of the result sortedMap
, which is Map<Integer, Integer>
.
Map.Entry.<Integer, Integer>comparingByValue()
gives the hints necessary to resolve it nicely.
Map.Entry.comparingByValue()
, as is, is a very vague thing to write.
Comparator<Map.Entry<Object, Comparable<Comparable<?>>>>
comparator = comparingByValue();
It becomes more meaningful when you give it a generic context.
Comparator<Map.Entry<Integer, Integer>>
comparator = comparingByValue();
In your case, it's important because Map.Entry.comparingByValue()
starts the chain, and the following instance methods (e.g. thenComparing
) will resolve their own generic parameters based on the generic parameters of the preceding method (here, comparingByValue
).
来源:https://stackoverflow.com/questions/58113660/what-is-the-importance-of-integer-integer-in-map-entry-integer-integercompa