结果:
代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class demo { public static void main(String[] args) throws IOException { String S = "马佳;刘胜;马佳;刘胜;慧;慧;刘胜;"; String str[] = S.split(";"); System.out.println(str.length); Map <String, Integer> map = new HashMap<String, Integer>(); for (String s1 : str) { if (!map.containsKey(s1)) map.put(s1, 1); else map.put(s1, (map.get(s1)+1)); } List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> mapping2, Map.Entry<String, Integer> mapping1) { return mapping1.getValue().compareTo(mapping2.getValue()); } }); Map.Entry<String, Integer> mapping = null; for (int i = 0 ;i<list.size() ;i++) { mapping = list.get(i); if (i<10) System.out.println(mapping.getKey() + "=" + mapping.getValue()); } } }