2017-08-11 62 views
1

我有List<Map.Entry<Double, Boolean>>功能。使用Java流来获取包含密钥的地图以及来自List的该密钥的出现次数

我想要计算列表中可能值Boolean的出现次数。

我已经做了当前的尝试是

Map<Boolean, List<Map.Entry<Double, Boolean>>> classes = 
    feature.stream().collect(Collectors.groupingBy(Map.Entry::getValue)); 

取而代之的Map<Boolean, List<Map.Entity<Double, Boolean>我想一个Map<Boolean, Integer>其中整数是出现的次数。

我已经试过

Map<Boolean, List<Map.Entry<Double, Boolean>>> classes = 
    feature.stream().collect(Collectors.groupingBy(Map.Entry::getValue, List::size)); 

但这抛出一个没有适合的方法功能。

我是新来的流API,所以任何帮助实现这一点将不胜感激!

+1

你叫什么'布尔值的可能值的出现次数',多少个真值和多少个假? –

+0

@AnthonyRaymond是啊,这就是我的意思,也可以用String或其他东西替换布尔值,如果出现在地图上,例如 – Rabbitman14

回答

1

其他的答案很好地工作,但如果你坚持要得到Map<Boolean,Integer>你需要这个:

Map<Boolean,Integer> result = feature.stream() 
      .map(Map.Entry::getValue) 
      .collect(Collectors.groupingBy(
       Function.identity(), 
       Collectors.collectingAndThen(Collectors.counting(), Long::intValue))); 
+1

Integer不需要长时间:)但是因为你是我问的唯一回答问题的人,我接受你的 – Rabbitman14

1

您可以使用地图函数来获得布尔和名单groupingBy它:

Map<Boolean, Long> collect = feature.stream() 
       .map(Map.Entry::getValue) 
       .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 
1

这会给你的Map<Boolean, Long>结果:

List<Map.Entry<Double, Boolean>> feature = new ArrayList<>(); 
Map<Boolean, Long> result = feature 
     .stream() 
     .map(Map.Entry::getValue) 
     .collect(Collectors.groupingBy(Function.identity(), 
       Collectors.counting())); 
+0

或'Collectors.partitioningBy()',则获得“Hello”和“World”的所有出现。 – shmosel