现有以下集合List<Map<String,String>>,
集合中元素Map中主要包含“code”,“name”等属性,
要求按code升序,name降序的顺序对集合进行重新排序;
实现Collections接口进行排序
1,先根据需求封装List<Map<String,String>>
public static void main(String[] args) {
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> mapOne = new HashMap<>();
("code", "001");
("name", "小a");
Map<String, String> mapTwo = new HashMap<>();
("code", "003");
("name", "小b");
Map<String, String> mapThree = new HashMap<>();
("code", "002");
("name", "小c");
(mapOne);
(mapTwo);
(mapThree);
//进行排序
List<Map<String, String>> listResult = listSort(list);
//控制台打印
for (Map<String, String> map : listResult) {
("编号:" + ("code") + ",姓名:" + ("name"));
}
}
2,根据问题,调用Conllections方法进行两次排序
public static List<Map<String, String>> listSort(List<Map<String, String>> list) {
//实现Collections接口进行排序
(list, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return ("code").compareTo(("code"));
}
});
//在对已经排序完成的进行降序
(list, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return -("name").compareTo(("name"));
}
});
return list;
}
关于compareTo用法:
/Soinice/article/details/80662732