使用Java8流从映射中查找最高值

使用Java8流从映射中查找最高值,java,java-8,java-stream,Java,Java 8,Java Stream,我编写了以下方法来查找映射到最高值的键,并尝试转换为javaStreams。你能帮忙吗 private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) { List<Integer> listMax = new ArrayList<Integer>(); Long frequency = 0L; for (Integer key : mapGroup.key

我编写了以下方法来查找映射到最高值的键,并尝试转换为java
Stream
s。你能帮忙吗

private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) 
{
    List<Integer> listMax = new ArrayList<Integer>();
    Long frequency = 0L;
    for (Integer key : mapGroup.keySet()) {
        Long occurrence = mapGroup.get(key);
        if (occurrence > frequency) {
            listMax.clear();
            listMax.add(key);
            frequency = occurrence;
        } else if (occurrence == frequency) {
            listMax.add(key);
        }
    }
    return listMax;
}
私有列表testStreamMap(Map mapGroup)
{
List listMax=new ArrayList();
长频率=0L;
for(整数键:mapGroup.keySet()){
长时间出现=mapGroup.get(键);
如果(发生率>频率){
listMax.clear();
listMax.add(键);
频率=发生率;
}else if(发生率==频率){
listMax.add(键);
}
}
返回listMax;
}

我不确定你一半的代码想做什么,但根据标题回答你的问题,我猜标题应该是“查找具有最高值的条目”:

Map.Entry maxEntry=Map.entrySet().stream()
.max(Map.Entry.comparingByValue()).get();

您可以通过

Integer max=mapGroup.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
但不幸的是,没有内置函数来获得所有等价的最大值

最简单、直接的解决方案是首先找到最大值,然后检索映射到该值的所有键:

private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) {
    if(mapGroup.isEmpty())
        return Collections.emptyList();
    long max = mapGroup.values().stream().max(Comparator.naturalOrder()).get();
    return mapGroup.entrySet().stream()
        .filter(e -> e.getValue() == max)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
}
私有列表testStreamMap(Map mapGroup){
if(mapGroup.isEmpty())
返回集合。emptyList();
long max=mapGroup.values().stream().max(Comparator.naturalOrder()).get();
返回mapGroup.entrySet().stream()
.filter(e->e.getValue()==max)
.map(map.Entry::getKey)
.collect(Collectors.toList());
}

在“”中讨论了在单个过程中获得流的所有最大值的解决方案。如果您的输入是一个普通的
Map
(例如
HashMap
),可以便宜地多次迭代,您会发现单遍解决方案要复杂得多,不值得付出努力。

您的问题不清楚,您称之为
occurrence
(顺便说一句,拼写错误)在第二个实现中调用
tempValue
。在第一个实现中命名为
frequencey
(也拼写错误)的参数在第二个实现中称为
occurrence
。从与您的姓名保持一致开始,这可能有助于您解决困惑。“出现率最高的键”?我猜您在调用
mapGroup.get(Key)
时试图找出出现率最高的“值”。对吗?@ShyamBaitmangalkar是的,试着找出发生率最高的密钥列表哈是的!!我能理解@波希米亚这只会返回单键,怎么会返回单键列表呢keys@dumy您是否希望所有条目共享相同的最大值?如果不是,什么“列表”(请举例)。@Bohemian让我们说,Map{key,value}={1,4},{2,3},{3,4},{4,3},那么返回列表应该是1和4,频率最高的是4。@Dumy你是说1和3(在你的例子中都有4)?
private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) {
    if(mapGroup.isEmpty())
        return Collections.emptyList();
    long max = mapGroup.values().stream().max(Comparator.naturalOrder()).get();
    return mapGroup.entrySet().stream()
        .filter(e -> e.getValue() == max)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
}