繁体   English   中英

如何从 LinkedHashMap 中获取具有“最佳”值的键

[英]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));
    }

大概的概念:

  • 遍历列表
  • 如果当前值“更好”,则将该值保存为“最佳”并将该值的密钥存储在 ArrayList“最佳密钥”中
  • 如果当前值“更差”,继续下一个
  • 如果当前值等于当前“最佳”,则 append 是“最佳键”列表的键

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM