java-8 - 从 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 来做到这一点。
解决方案
您可以使用groupingBy和findFirst方法。因此代码如下所示:
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);
我在这篇文章中找到了这个答案。
推荐阅读
- html - 如何在 django html 模板中添加 if 函数
- odoo - 无法在 Odoo 12 EE 中向 Many2many 添加项目
- spring-mvc - 为什么在spring mvc中配置很多servlet
- python - python输入到另一个.py文件
- typescript - 通知 typescript 函数抛出了异常
- c# - 转换在 LINQ 对象中创建的值
- javascript - 在 angularjs ui-select 指令中更新后,如何默认设置搜索字段中的更新值?
- angular - 生成命令需要在 Angular 项目中运行,但找不到项目定义
- ruby-on-rails - Rails 5.2 - 如何将报表模型与两个用户相关联
- android - Revision not found in React-Native,Android