HashMap的两种排序方法

排序方法1:

public class Sort1 {
	public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("d", 2);
		map.put("c", 1);
		map.put("b", 1);
		map.put("a", 3);
		List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				// return (o1.getValue() - o2.getValue());
				return (o1.getKey()).toString().compareTo(o2.getKey());
			}
		});
		for (int i = 0; i < infoIds.size(); i++) {
			String id = infoIds.get(i).toString();
			System.out.println(id);
		}
	}
}

排序方法2:

public class Sort2 {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("a0201", "1201");
		map.put("c01", "41");
		map.put("b0304", "3304");
		map.put("d0101", "2101");
		Object[] key = map.keySet().toArray();
		Arrays.sort(key);
		for (int i = 0; i < key.length; i++) {
			System.out.println(key[i] + " = " + map.get(key[i]));
		}
	}
}


你可能感兴趣的:(java,排序,HashMap,sort)