I just begin to learn Streams, and I have a task to count and sort all words in some array of String. I have already parsed my input to words, but I don't know how to add and update entry using the stream.
There is my parsing stream:
Stream<String> stringStream = lines.stream().flatMap(s -> Arrays.stream(s.split("[^a-zA-Z]+")));
String[] parsed = stringStream.toArray(String[]::new);
I have done this task without streams just like this:
Map 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 class:
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;
}
}
