-3

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

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

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

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

1 回答 1

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

    }
}
于 2013-03-28T12:41:37.790 回答