![](/img/trans.png)
[英]How to Compare 2 LinkedHashMap and get difference in keys & values?
[英]How can I get the keys with the 'best' values from a LinkedHashMap
我有一个问题:我的 HashMap 看起来像:
[1,2,3,4] , 5
[1,3,3,4] , 2
[1,2,5,4] , -1
[1,2,4,4] , -1
我想对这个 hashmap 进行排序,它成功了! 我得到一个LinkedHashMap
回来。 我想要的是获得具有最佳“价值”的钥匙。 最好的“值”是小数,在本例中为 -1。 是否可以选择返回int[][]
键[1,2,5,4] and [1,2,4,4]
? 例如,如果最佳值为 3 并且它出现 5 次,它应该给我 5 个键。 仅等于一个最佳值。 我怎么能那样做?
HashMap<int[], Double> hashMap = new HashMap<int[], Double>();
value = sortHashMap(hashMap);
int[][] bestKey;
// bestkey = value.getTheKeysWithTheBestValue // how could I do that? :(
// bestKey should be
// [ [1,2,5,4], [1,2,4,4] ]
private LinkedHashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
list.sort(Entry.comparingByValue());
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(key1, key2) -> key2, LinkedHashMap::new));
}
大概的概念:
Use Collections.min(yourMap.values())
to get the min
value, stream over the entry set of your map and filter entries having the same value as the min
value, map entries to keys and collect to array:
int[][] bestKeys = yourMap.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(Collections.min(myMap.values())))
.map(Map.Entry::getKey)
.toArray(int[][]::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.