首页 > 解决方案 > 从 Java 8 中的 Map 过滤并返回值

问题描述

我正在学习 Java 8 基础知识,并且正在努力解决一个简单的问题。我有一个程序,它基本上给了我数组中的非重复元素。实现这一点的实现逻辑在这里无关紧要;我正在努力返回 Java 8 中的值。

public class Tetst
 {
  public static void main(String[] args)
{
    int[] arr = {1,2,2};
    singleNumber(arr);
}

public static int singleNumber(int[] nums) {
    HashMap<Integer,Integer> map = new HashMap<>();
    //int val = 0;
    for(int i = 0; i < nums.length; i++) {
        if(!map.containsKey(nums[i])) {
            map.put(nums[i], 1);
        } else {
            map.put(nums[i], map.get(nums[i]) + 1);
        }
    }

    return map.entrySet()
        .stream()
        .filter(val -> val.getValue().equals(1))

    //         for(Map.Entry<Integer, Integer> entrySet : map.entrySet()) {
    //             if(entrySet.getValue().equals(1)) {
    //                 val = entrySet.getKey();
    //             }
    //         }

    //         return val;

}

}

我知道我必须过滤结果,但是我如何返回这个地图的特定键。在评论部分,我能够使用 Java 7 来做到这一点。

标签: java-8java-stream

解决方案


您可以使用groupingByfindFirst方法。因此代码如下所示:

List<Integer> nums = List.of(1, 2, 2);
Map<Integer, Long> counts = nums.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return counts.entrySet().stream().filter(val -> val.getValue().equals(1L)).map(Entry::getKey).findFirst().orElse(-1);

我在这篇文章中找到了这个答案。


推荐阅读