For some reason, I have constant access to the "Java word counting program" in my program every day. So, I posted the code posted on that blog I wrote it more than 10 years ago, but when I look at it now, I'm embarrassed that I don't use the generic type for List, and there are various immature parts.
Before.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class WordCounterTable {
private Map counterTable;
public WordCounterTable(){
this.counterTable = new HashMap();
}
public void count(List list){
for(Iterator ite = list.iterator();ite.hasNext();){
Object target = ite.next();
if(this.counterTable.get(target) == null){
this.counterTable.put(target,new Integer(1));
}else{
this.counterTable.put(target,
new Integer(
((Integer)this.counterTable.get(target)).intValue()+1)
);
}
}
}
public String printTableValue(){
StringBuffer buf = new StringBuffer();
for(Iterator ite = this.counterTable.keySet().iterator();ite.hasNext();){
Object key = ite.next();
buf.append("word:"+key+" count:"+this.counterTable.get(key)+"\n");
}
return buf.toString();
}
}
So, I can't keep posting such an embarrassing program on my blog forever, so I rewrote it using the Stream function of Java8.
WordCount.java
package test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;
public class WordCount {
public static void main(String args[]){
List<String> list = Arrays.asList("triple","evergreen","puisan","triple","puisan");
Map<String,Integer> map = list.stream().collect(
Collectors.groupingBy(
//Set the List element as it is in the Map key
Function.identity(),
//Replace the List element with 1 for the Map value so that it counts
Collectors.summingInt(s->1))
);
System.out.println(map);
}
}
//{triple=2, puisan=2, evergreen=1}Is output to the console
The Stream function is convenient, isn't it? Compared to the previous light program, the logic is cleaner and it looks beautiful.
Recommended Posts