Map按照key进行排序

声明比较器:

class MapKeyComparator implements Comparator {
	@Override
	public int compare(Integer o1, Integer o2) {
		return o2 - o1;
	}
}

排序方法:

public static Map> sortMapByKey(Map> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map> sortMap = new TreeMap<>(new MapKeyComparator());
		sortMap.putAll(map);
		return sortMap;
	}

进行测试(偷了个懒,上一个博客的代码直接粘过来用了):

public static void main(String[] args) {
		List list = new ArrayList<>();
		list.add(new User(1, 1));
		list.add(new User(1, 2));
		list.add(new User(3, 1));
		list.add(new User(2, 1));
		list.add(new User(2, 3));
		list.add(new User(2, 2));
		Map> map = new HashMap<>();
		for(User user : list){
			if(map.containsKey(user.getId())){//map中存在此id,将数据存放当前key的map中
				map.get(user.getId()).add(user);
			}else{//map中不存在,新建key,用来存放数据
				List tmpList = new ArrayList<>();
				tmpList.add(user);
				map.put(user.getId(), tmpList);
			}
		}
		System.out.println("原Map:"+map.toString());
		Map> rmap = sortMapByKey(map);
		System.out.println("排序后:"+rmap.toString());
	}

运行结果:

你可能感兴趣的:(JAVA)