如何计算Java中列表对象中的重复值?

时间:2013-03-28 12:30:01

标签: java arrays count

在java中,我有一个像这样的数组:

String[] city = {"texas", "ny", "sydney", "ny", "paris", "texas", "ny"};

我想用计数对它们进行排序/分组......比如 -

texas = 2
ny = 3
sydney = 1
paris = 1

1 个答案:

答案 0 :(得分:10)

使用Collections.frequency()方法。

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test{
    public static void main(String[] args) {
        String[] city = {"texas", "ny", "sydney", "ny", "paris", "texas", "ny"};
        List<String> asList = Arrays.asList(city);
        Map<String, Integer> map= new HashMap<String, Integer>();
        for(String s: city){
            map.put(s,Collections.frequency(asList,s));
        }
        System.out.println(map);

    }
}