1.对list集合中某个字段进行操作
eg:将时间类型转成毫秒值
list.parallelStream().forEach(x ->{
x.setLongTime(x.getTime()!=null ? x.getTime() : 0);
});
2.对集合排序
eg:对List<User>中用户姓名首字母排序
// 以前常规方式
Collections.sort(userList, new Comparator<User>() {
public int compare(User o1, User o2) {
String name1 = o1.getFristLetter().toString();
String name2 = o2.getFristLetter().toString();
return name1.compareTo(name2);
}
});
// 使用lambda表达式
Collections.sort(userList,(o1,o2)->o1.getFristLetter().toString().compareTo(o2.getFristLetter().toString()));
3.条件过滤list数据
// 过滤出年龄大于18岁的用户
list = list.stream().filter(u -> u.getAge()>=18).collect(toList());
4.对集合的结果进行去重
// 去除相同名称的用户
List<UserVO> list
= userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserVO::getUserName))), ArrayList::new));
参考博客:https://www.jianshu.com/p/11c925cdba50
总结:使用lambda表达式十分简洁,减少了很多代码,开发更方便。