Cso*_*agy 1 java hashmap java-8 java-stream method-reference
我有一个练习要解决.我有一个Fox类,它有名字和颜色字段.我的练习是按颜色找出狐狸的频率.
因此我创建了一个HashMap,其中String属性将是狐狸名称,而Integer将是它本身的出现:
Map<String, Integer> freq = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
完成后,我一直在尝试用流编写代码,但我正在努力做到这一点.我写了这样的东西:
foxes.stream()
.map(Fox::getColor)
.forEach()
//...(continued later on);
Run Code Online (Sandbox Code Playgroud)
,其中狐狸是一个清单.
我的问题基本上是语法.如果颜色没有出现,我想做一些事情
freq.put(Fox::getName, 1)
Run Code Online (Sandbox Code Playgroud)
其他
freq.replace(Fox::getName, freq.get(Fox::getName) + 1)
Run Code Online (Sandbox Code Playgroud)
我该怎么把它放在一起?
我不建议继续你的方法只是因为已经有一个内置的收集器为这个groupingBy收集器与counting()下游:
Map<String, Long> result = foxes.stream()
.collect(Collectors.groupingBy(Fox::getName, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)
通过"名称"查找频率,同样,您可以通过更改分类功能按颜色获取频率.
foxes.stream()
.collect(Collectors.groupingBy(Fox::getColor, Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)