2017-09-14 71 views
4

我正在嘗試計算已選擇的不同文章中關鍵字的出現次數。 我可以在java 7中做到這一點,但在java 8中掙扎。計算多篇文章中的關鍵字出現次數

結構是這樣的。

關鍵字類

public class Keyword { 

    private String word; 
    private int value; 
} 

Article類

public class Article { 
    private Set<Keyword> keywordsList; 
    private boolean selected; 
} 

我怎麼算我有A,B,C,...等的時間數量。關鍵字

Map<Keyword,Integer> occurrenceMapping = new HashMap<>(); 

final Set<Article> articleSetFiltered = articleSet.stream() 
      .filter(a -> a.isSelected()) 
      .collect(Collectors.toSet()); 

    for(Article a : articleSetFiltered) { 
     for(Keyword k : a.getKeywordsList()) { 
      if(!occurrenceMapping.containsKey(k)) { 
       occurrenceMapping.put(k,1); 
      } 
      else{ 
       final int occurrence = occurrenceMapping.get(k); 
       occurrenceMapping.put(k,occurrence+1); 
      } 
     } 
    } 

我開始做這樣的事情。仍然圍繞着它,但不知道我正在朝着好的方向前進:/如果有人能指引我朝着正確的方向發展,那會很棒!

Map<Keyword,Integer> occurenceMappingBis = articleSetFiltered = articleSet.stream() 
      .filter(a -> a.isSelected()) 
      .forEach(
      article -> article.getKeywordsList() 
        .stream().collect(Collectors.groupingBy(keyword -> keyword, Collectors.counting())) 
    ); 

回答

5

就像這樣(我還沒有編譯它,但應該工作)。這假設Keyword重寫hashcode/equals

articleSet.stream() 
      .filter(Article::isSelected) 
      .flatmap(ar -> ar.getKeywordsList().stream()) 
      .collect(Collectors.groupingBy(
        Function.identity(), 
        Collectors.counting())); 
+0

關鍵字會覆蓋hashcode/equals方法。謝謝。我會試一試 – kanadianDri3