List<Map<String,Object>> 集合根据Map里的某个值大小进行排序
实现代码:
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;
public class hhh {
public static void main(String[] args) throws UnknownHostException, SocketException {
List<Map<String, Object>> listResult = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new LinkedHashMap<String, Object>();
map1.put("sort", 3);
map1.put("name", "小明");
map1.put("id", "1");
listResult.add(map1);
Map<String, Object> map2 = new LinkedHashMap<String, Object>();
map2.put("sort", 4);
map2.put("name", "小李");
map2.put("id", "2");
listResult.add(map2);
Map<String, Object> map3 = new LinkedHashMap<String, Object>();
map3.put("sort", 1);
map3.put("name", "小王");
map3.put("id", "3");
listResult.add(map3);
Map<String, Object> map4 = new LinkedHashMap<String, Object>();
map4.put("sort", 2);
map4.put("name", "小赵");
map4.put("id", "4");
listResult.add(map4);
System.out.println("排序前:");
for (Map<String, Object> map : listResult) {
System.out.println("sort:" + map.get("sort") + " name:" + map.get("name") + " id:" + map.get("id"));
}
Collections.sort(listResult, new MapComparatorDesc());
System.out.println("根据sort值降序:");
for (Map<String, Object> map : listResult) {
System.out.println("sort:" + map.get("sort") + " name:" + map.get("name") + " id:" + map.get("id"));
}
Collections.sort(listResult, new MapComparatorAsc());
System.out.println("根据sort值升序:");
for (Map<String, Object> map : listResult) {
System.out.println("sort:" + map.get("sort") + " name:" + map.get("name") + " id:" + map.get("id"));
}
}
/**
* 降序
*/
static class MapComparatorDesc implements Comparator<Map<String, Object>> {
@Override
public int compare(Map<String, Object> m1, Map<String, Object> m2) {
Integer v1 = Integer.valueOf(m1.get("sort").toString());
Integer v2 = Integer.valueOf(m2.get("sort").toString());
if (v2 != null) {
return v2.compareTo(v1);
}
return 0;
}
}
/**
* 升序
*/
static class MapComparatorAsc implements Comparator<Map<String, Object>> {
@Override
public int compare(Map<String, Object> m1, Map<String, Object> m2) {
Integer v1 = Integer.valueOf(m1.get("sort").toString());
Integer v2 = Integer.valueOf(m2.get("sort").toString());
if (v1 != null) {
return v1.compareTo(v2);
}
return 0;
}
}
}
运行结果: