使用lambda对map进行排序

最近在学习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;
}

你可能感兴趣的:(lambda)