业务中,我们经常会有队map进行排序的要求,如下将会详细讲解如何利用java8的lambda表达式实现map的内部排序。
首先,我们先构造一个person类:
public class Person {
private String addr;
private String age;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Person(String addr, String age) {
this.addr = addr;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"addr='" + addr + '\'' +
", age='" + age + '\'' +
'}';
}
}
测试,对map进行排序处理。
import com.ky.common.Person;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;
public class Test {
public static void main(String[] args) {
final ConcurrentHashMap map = new ConcurrentHashMap<>();
Person p = new Person("河南周口","25");
map.put("xiaofei", p);
Person p1 = new Person("内蒙古","24");
map.put("gq", p1);
Person p2 = new Person("江苏扬州","22");
map.put("wangfeng", p2);
Person p3 = new Person("安徽合肥","26");
map.put("xiaowei", p3);
//方法1
final LinkedHashMap collect = map.entrySet().stream().sorted(comparingByValue(new Comparator() {
@Override
public int compare(Person o1, Person o2) {
return Integer.valueOf(o1.getAge()).compareTo(Integer.valueOf(o2.getAge()));
}
})).collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));
//方法2
ConcurrentHashMap collect1 = map.entrySet().stream().sorted(new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
return Integer.valueOf(o1.getValue().getAge()).compareTo(Integer.valueOf(o2.getValue().getAge()));
}
}).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, ConcurrentHashMap::new));
//方法3
Stream> st = map.entrySet().stream();
Comparator> com=new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
return Integer.valueOf(o1.getValue().getAge()).compareTo(Integer.valueOf(o2.getValue().getAge()));
}
};
st.sorted(com).forEachOrdered(e->map.put(e.getKey(),e.getValue()));
//方法4
stream.sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,(e1, e2)->e2, ConcurrentHashMap::new));
map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(System.out::println);
final Collection values = collect.values();
System.out.println(values);
}
}