Java 在HashMap中查找匹配的键和值

Java 在HashMap中查找匹配的键和值,java,hashmap,Java,Hashmap,在我的程序中,我遇到了类似test#6:leastCommon({})exp的错误。异常:IllegalArgumentException您的异常第16行堆栈跟踪上的NoSuchElementException:NoSuchElementException leastCommon,第16行结果:fail public static int leastCommon(Map<String, Integer> map) { Map<Integer, Integer> r

在我的程序中,我遇到了类似test#6:leastCommon({})exp的错误。异常:IllegalArgumentException您的异常第16行堆栈跟踪上的NoSuchElementException:NoSuchElementException leastCommon,第16行结果:fail

public static int leastCommon(Map<String, Integer> map) {
    Map<Integer, Integer> result = new TreeMap<Integer, Integer>();
    Iterator<String> i = map.keySet().iterator();
    
    while (i.hasNext()) {
        int num = map.get(i.next());
        if (result.containsKey(num)) {
            result.put(num, result.get(num) + 1);
        } else {
            result.put(num, 1);
        }
    }
    
    Set<Integer> setKey = result.keySet();
    Iterator<Integer> i1 = setKey.iterator();
    int min = i1.next();
    
    while(i1.hasNext()) {
        int current = i1.next();
        if (result.get(current) < result.get(min)) {
            min = current;
        }
    }
    
    return min;
公共静态int-leastCommon(映射){
映射结果=新树映射();
迭代器i=map.keySet().Iterator();
while(i.hasNext()){
int num=map.get(i.next());
if(result.containsKey(num)){
result.put(num,result.get(num)+1);
}否则{
结果:put(num,1);
}
}
Set setKey=result.keySet();
迭代器i1=setKey.Iterator();
int min=i1.next();
while(i1.hasNext()){
int current=i1.next();
if(result.get(当前)
}


如何使用我的程序进行更正?

当输入映射为空且
min=i1时,问题似乎发生在边缘情况下。next()
尝试查找某些内容

这可以通过简单地检查/断言输入参数来解决,并且可能值得返回
Integer
,而不是取消装箱到原语
int

public静态整数leastCommon(映射){
if(null==map | | map.isEmpty()){
返回null;//或抛出IllegalArgumentException
}
//…保留代码的其余部分
}

但是,使用流API解决此任务会更简单,使用
收集器计算输入映射中每个值的频率。groupingBy
收集器。计算
并查找频率较低的条目:

public静态整数leastCommon(映射){
if(null==map)返回null;
返回map.values().stream()
.collect(Collectors.groupingBy(x->x,Collectors.counting())
.entrySet().stream()
.min(Map.Entry.comparingByValue())
.map(map.Entry::getKey)
.orElse(空);
}

请提供一个。哪一行是16?