从一个list<map> 根据指定的map字段进行排序
package yulisao.test;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* @author yulisao
* @createDate 2022/3/20 0020 下午 11:34
*/
public class MapListSort {
public static void main(String[] args) {
List<Map<String, Object>> list = initMapList();
sortByFeild(list, "age", "desc");
System.out.println("按年纪取最大的一条数据,其姓名是:" + list.get(0).get("name"));
}
/**
* List<Map>根据map字段排序
*
* @param list
* @param feild 排序字段
* @param sortTyp 排序方式 desc-倒序 asc-正序
* @return
*/
private static List<Map<String, Object>> sortByFeild(List<Map<String, Object>> list, String feild, String sortTyp) {
if (CollectionUtils.isNotEmpty(list)) {
list.sort((m1, m2) -> {
if (StringUtils.equals(sortTyp, "desc")) {
return String.valueOf(m2.get(feild)).compareTo(String.valueOf(m1.get(feild)));
} else {
return String.valueOf(m1.get(feild)).compareTo(String.valueOf(m2.get(feild)));
}
});
// 或者 Collections类里面的sort方法也是list.sort()与上面一样
// Collections.sort(list, (m1, m2)-> String.valueOf(m1.get(feild)).compareTo(String.valueOf(m2.get(feild)))); // lamuda排序
}
return list;
}
private static List<Map<String, Object>> initMapList() {
List<Map<String, Object>> lists = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("name", "王五");
map.put("age", 55);
map.put("mobile", "15900001112");
lists.add(map);
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "李四");
map1.put("age", 18);
map1.put("mobile", "15900001111");
lists.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "赵六");
map2.put("age", 58);
map2.put("mobile", "13700001111");
lists.add(map2);
return lists;
}
}
这个排序仍是借助jdk包里面的方法实现,同样的如果list的元素类型是字符串、javabean等等, 修改一下compareTo两边要比较的对象即可
|