Counting keyword occurrences in multiple articles

Viewed 79

I'm trying to count occurrences of keywords in different articles that have been selected. I can do this in java 7 but struggling in java 8.

The structure is like this.

Keyword class

public class Keyword {

    private String word;
    private int value;
}

Article class

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

How I count the number of time I have A,B,C,...etc. keyword

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);
            }
        }
    }

I started doing something like this. Still working around it but not sure I'm going in the good direction :/ If someone could direct me in the right direction, that would be great!

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