搜索
您的当前位置:首页Map按照key进行排序

Map按照key进行排序

来源:乌哈旅游

声明比较器:

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

排序方法:

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

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

public static void main(String[] args) {
		List<User> 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<Integer, List<User>> 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<User> tmpList = new ArrayList<>();
				tmpList.add(user);
				map.put(user.getId(), tmpList);
			}
		}
		System.out.println("原Map:"+map.toString());
		Map<Integer, List<User>> rmap = sortMapByKey(map);
		System.out.println("排序后:"+rmap.toString());
	}

运行结果:

因篇幅问题不能全部显示,请点此查看更多更全内容

Top