Keyword Counting in Multiple Articles

I am trying to count the number of keywords in different articles that have been selected. I can do this in java 7, but I'm afraid in java 8.

The structure is as follows.

Keyword class

public class Keyword {

    private String word;
    private int value;
}

Article class

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

How do I count the amount of time that 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 to do something like this. Still working around, but not sure if I will go in a good direction: / If someone can direct me in the right direction, it will 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()))
    );
+4
source share
1 answer

Something like this (I did not compile it, but should work). This suggests Keywordredefining hashcode/equals.

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

Source: https://habr.com/ru/post/1685680/


All Articles