java中对包含汉字的集合使用sort进行重新排序

先创建一个List集合

       List> list = new ArrayList<>();
		
		Map map1 = new HashMap<>();
		map1.put("code", "ays5h2");
		map1.put("name", "孙悟空");
		map1.put("age", 600);
		list.add(map1);
		
		Map map2 = new HashMap<>();
		map2.put("code", "brse7f");
		map2.put("name", "猪八戒");
		map2.put("age", 700);
		list.add(map2);
		
		Map map3 = new HashMap<>();
		map3.put("code", "brse7f");
		map3.put("name", "唐僧");
		map3.put("age", 42);
		list.add(map3);
		
		Map map4 = new HashMap<>();
		map4.put("code", "twdf0");
		map4.put("name", "沙悟净");
		map4.put("age", 650);
		list.add(map4);

打印该List集合,结果为

[{code=ays5h2, name=孙悟空, age=600}, {code=brse7f, name=猪八戒, age=700}, {code=brse7f, name=唐僧, age=42}, {code=twdf0, name=沙悟净, age=650}]

1、根据code和name正序排序

Collections.sort(list, new Comparator>(){
	public int compare(Map s1,Map s2) {
		if(s1.get("code").toString().compareTo(s2.get("code").toString())==0) {
			return                 Collator.getInstance(Locale.CHINA).compare(s1.get("name"),s2.get("name"));
		}else {
			return s1.get("code").toString().compareTo(s2.get("code").toString());
		}
	}
});

打印结果:[{code=ays5h2, name=孙悟空, age=600}, {code=brse7f, name=唐僧, age=42}, {code=brse7f, name=猪八戒, age=700}, {code=twdf0, name=沙悟净, age=650}]

2、code正序排序,name倒叙排序

Collections.sort(list, new Comparator>(){
	public int compare(Map s1,Map s2) {
		if(s1.get("code").toString().compareTo(s2.get("code").toString())==0) {
			return 0 - Collator.getInstance(Locale.CHINA).compare(s1.get("name"),s2.get("name"));
		}else {
			return s1.get("code").toString().compareTo(s2.get("code").toString());
		}
	}
});

打印结果:[{code=ays5h2, name=孙悟空, age=600}, {code=brse7f, name=猪八戒, age=700}, {code=brse7f, name=唐僧, age=42}, {code=twdf0, name=沙悟净, age=650}]

你可能感兴趣的:(java中对包含汉字的集合使用sort进行重新排序)