2017-08-11 11 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

相關問題