扬帆大鱼
自己实现一个comparator,按照自己的需求,给出比较结果。我写了一个,可以参考一下:
package com.tc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by tianchi on 2017/9/6.
*/
public class Ripper {
public static void main(String[] args) {
Map map = new HashMap();
map.put("name", "ZK");
map.put("age", 13);
Map map2 = new HashMap();
map2.put("name", "ZA");
map2.put("age", 15);
Map map3 = new HashMap();
map3.put("name", "CX");
map3.put("age", 20);
Map map4 = new HashMap();
map4.put("name", "CX");
map4.put("age", 18);
List> list = new ArrayList>();
list.add(map);
list.add(map2);
list.add(map3);
list.add(map4);
Stream> stream = list.stream();
List> list2 = stream.sorted(Ripper::comparator).collect(Collectors.toList());
for (Map m : list2) {
System.out.println(m.get("name") + " " + m.get("age"));
}
}
public static int comparator(Map map1, Map map2) {
if (map1 == null && map2 == null)
return 0;
if (map1 == null || map2 == null) {
throw new NullPointerException();
}
String name1 = (String) map1.get("name");
String name2 = (String) map2.get("name");
int c = name1.compareTo(name2);
if (c != 0)
return c;
int age1 = (int) map1.get("age");
int age2 = (int) map2.get("age");
return age2 - age1;
}
}
输出如下:
CX 20
CX 18
ZA 15
ZK 13