0
Follow
0
View

How to add and update map entry using Java Streams API

dzy213127 注册会员
2023-01-25 21:41

A simple approach is collecting toMap() with a merge function:

Map<String, WordStatistics> wordToFrequencyMap = lines.stream()
        .map(s -> s.split("[^a-zA-Z]+"))
        .flatMap(Arrays::stream)
        .collect(Collectors.toMap(w -> w, w -> new WordStatistics(w, 1), (ws1, ws2) -> {
            ws1.setFreq(ws1.getFreq() + ws2.getFreq());
            return ws1;
        }));

To break down the toMap() arguments:

  • w -> w just means use the stream element as the map key.
  • The next argument produces a value for the key, which is initially a new instance of WordStatistics with a frequency of 1.
  • Finally, we tell the collector how to merge values together when they belong to the same key. In our case, we sum the frequencies into one of the values (ws1) and return that as the merge result.
edxsunlixin 注册会员
2023-01-25 21:41

This should do pretty much the same you are doing in your loop right now.

Pattern pattern = Pattern.compile("[^a-zA-Z]+");
lines.stream().flatMap(pattern::splitAsStream).filter(s -> s.length() > 3).forEach(s -> {
    WordStatistics tmp = wordToFrequencyMap.get(s);
    if (tmp == null) {
        wordToFrequencyMap.put(s, new WordStatistics(word, 1));
    } else {
        tmp.setFreq(tmp.getFreq() + 1);
    }
});

About the Author

Question Info

Publish Time
2023-01-25 21:40
Update Time
2023-01-25 21:40