LoginSignup
6
1

More than 5 years have passed since last update.

Listに含まれる単語の数をカウントするプログラム

Last updated at Posted at 2017-07-01

自分のプログに載せた「Javaの単語をカウントをするプログラム」になぜか、毎日コンスタントにアクセスされている。
で、そのブログに載せたコードを転記してみた
10年以上前に書いたものだが、今、見ると、Listに総称型を使っていないとか、色々、未熟な部分があって恥ずかしいですね。

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();
    }
}

で、いつまでもこんな恥ずかしいプログラムをいつまでもブログに載せておくわけにもいかないので、Java8のStream関数を使って、書き換えてみました

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(
                        //MapのキーにはListの要素をそのままセットする
                        Function.identity(),
                        //Mapの値にはListの要素を1に置き換えて、それをカウントするようにする
                        Collectors.summingInt(s->1)) 
                );
        System.out.println(map);
    }
}
//{triple=2, puisan=2, evergreen=1}がコンソールに出力される

Stream関数、便利ですね。
以前のもっさりしたプログラムに比べて、ロジックがすっきりかけていて見た目も美しくなっています

6
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1