![](/img/trans.png)
[英]How to merge lists of Map with Lists values using Java Streams API?
[英]How to add and update map entry using Java Streams API
我剛開始學習 Streams,我有一項任務是對某個字符串數組中的所有單詞進行計數和排序。 我已經將我的輸入解析為單詞,但我不知道如何使用流添加和更新條目。
有我的解析流:
Stream<String> stringStream = lines.stream().flatMap(s -> Arrays.stream(s.split("[^a-zA-Z]+")));
String[] parsed = stringStream.toArray(String[]::new);
我在沒有流的情況下完成了這個任務,就像這樣:
Map<String,WordStatistics> wordToFrequencyMap = new HashMap<>();
for (String line: lines) {
line=line.toLowerCase();
String[] mas = line.split("[^a-zA-Z]+");
for (String word:mas) {
if(word.length()>3) {
if (!wordToFrequencyMap.containsKey(word)) {
wordToFrequencyMap.put(word, new WordStatistics(word, 1));
} else {
WordStatistics tmp = wordToFrequencyMap.get(word);
tmp.setFreq(tmp.getFreq() + 1);
}
}
}
}
WordStatistics 類:
public class WordStatistics implements Comparable<WordStatistics>{
private String word;
private int freq;
public WordStatistics(String word, int freq) {
this.word = word;
this.freq = freq;
}
public String getWord() {
return word;
}
public int getFreq() {
return freq;
}
public void setWord(String word) {
this.word = word;
}
public void setFreq(int freq) {
this.freq = freq;
}
@Override
public int compareTo(WordStatistics o) {
if(this.freq > o.freq)
return 1;
if(this.freq == o.freq)
{
return -this.word.compareTo(o.word);
}
return -1;
}
}
一個簡單的方法是使用合並函數收集toMap()
:
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;
}));
這應該與您現在在循環中所做的幾乎相同。
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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.