最近在学习lambda表达式,记录一下
public static void main(String[] args) { Map<String, User> map = new HashMap<>(); map.put("1", new User("zhangsan", 17)); map.put("2", new User("lisi", 10)); map.put("3", new User("wangwu", 20)); map.put("4", new User("zhaoliu", 19)); // 排序前 map.forEach((key, value) -> System.out.println("key: " + key + ", value:" + value)); map = map.entrySet().stream() .sorted(Map.Entry.comparingByValue(comparingInt(User::getAge))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); // 排序后 map.forEach((key, value) -> System.out.println("key: " + key + ", value:" + value)); }User类
@Data public class User{ private String name; private int age; }排序方法
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); }