我试着在Java 8流API中找到一种简单的方法来进行分组,我用这种复杂的方式出来了!
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, List<String>> collect = list.stream().collect(
Collectors.groupingBy(o -> o));
System.out.println(collect);
List<String[]> collect2 = collect
.entrySet()
.stream()
.map(e -> new String[] { e.getKey(),
String.valueOf(e.getValue().size()) })
.collect(Collectors.toList());
collect2.forEach(o -> System.out.println(o[0] + " >> " + o[1]));
Run Code Online (Sandbox Code Playgroud)
我很感激你的意见.
我需要计算一些特殊捆绑包的出现次数。
Map<Integer,Integer> countBundles(){
return bundles.stream()
.bla()
.bla()
.bla()
.collect(groupingBy(Bundle::getId), counting()));
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译,因为计数返回 Long。有什么漂亮的方法返回 Map<Integer, Integer> 吗?
我有这个想法,但是很难看
map.entrySet().stream()
.collect(toMap(Map.Entry::getKey, entry -> (int) entry.getValue().longValue()));
Run Code Online (Sandbox Code Playgroud) 我是java的新手.我正在尝试从包含showNames的流创建一个HashMap.我的问题是,名称可能是重复的,它们可能会出现多次,这意味着它们必须映射到相同的键上,我在映射后尝试使用过滤器,但我不确定要放置什么条件.X-> x.equals(x)的?流showNames的外观如下:
LOTR,Lucifer,Breaking Bad,LOTR,Exorcist,The Godfather,The Godfather,Lucifer,等等
哈希映射应该具有显示名称的键,以及字符串在流中显示的时间值