最初のステップは、List コレクション内の各要素の出現数をカウントすることです。
/**
* 统计List集合中每个元素出现的次数
* 例如list(["111","111","222","333"])
* ->
* 则返回Map {111=2, 222=1, 333=1}
* @param falcons
* @return Map<String,Integer>
*/
public static Map<String, Long> frequencyOfListQ(List<String> falcons){
if(falcons.isEmpty()){
return new HashMap<>();
}
return falcons.stream().collect(Collectors.groupingBy(k->k, Collectors.counting()));
}
2 番目のステップでは、Map 内の最大出現数を計算し、Map<K, V> の Value (値) の最大値を見つけます。
/**
* @TODO : 求Map<K,V>中Value(值)的最大值 返回记录数据
* @AUTH : linfeng
* @DATE : 2022年9月22日 上午11:35:22
* @return_type : Map<String,Long>
* @param map
* @return
*/
public static Map<String ,Long> getMaxValue(Map<String, Long> map){
if(map == null){
return new HashMap<>();
}
Map<String,Long> maxMap = new HashMap<>();
int length =map.size();
Collection<Long> c = map.values();
Object[] obj = c.toArray();
Arrays.sort(obj);
for(Map.Entry<String,Long> entry : map.entrySet()){
if(entry.getValue() == obj[length-1]){
maxMap.put(entry.getKey(),entry.getValue());
}
}
return maxMap;
}