整理下工作中经常要用到的lambda表达式,熟练使用绝对有效提高工作效率,减少代码行数

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

从List<Object>对象列表中获取对象单个字段组成的新List
List<User> userList:获取所有用户的Id列表:
List<Long> userIdList = userList.stream.map(User::getUserId).collect(Collectors.toList());


foreach循环-修改对象列表中对象字段值
List<User> userList;//获取所有用户的Id列表
userList.foreach(User -> User.setUserId(User.getUserId+1));
foreach循环-修改对象中多个参数值
userList.foreach((x) -> {x.setUserId(0L); x.setUserName(""); x.setUserSex(0);})

List过滤值
List<String> list//Integer,Long等基本数据类型
过滤null值:
list.stream.filter(x -> x != null).collect(Collectors.toList());
过滤特定值(包括空字符串"")
list.stream.filter(x -> !"str".equals(x)).collect(Collectors.toList());

逗号分隔的字符串转List<Long>
List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

List<Long>转逗号分隔的字符串
1. Apache Commons的StringUtils
String str = StringUtils.join(list.toArray(), ",");
2. 利用Guava的Joiner
String str = Joiner.on(",").join(list);
3. 利用Spring Framework的StringUtils
String str = StringUtils.collectionToDelimitedString(list, ",");

List转Map
List<FlowNodeTimeoutRuleUser> userList;
1.List对象中两个字段对应
Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(FlowNodeTimeoutRuleUser::getUserId, FlowNodeTimeoutRuleUser::getUserName));
2.List对象中字段和对象本体对应
Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(FlowNodeTimeoutRuleUser::getUserId, x -> x));
本体表达式可以用lambda表达式x->x 也可以使用接口Function.identity()
Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(FlowNodeTimeoutRuleUser::getUserId, Function.identity()));
3. List对象中key字段重复导致错误,增加一个lambda表达式(key1, key2) -> key2,后者覆盖前者解决key重复问题
Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(FlowNodeTimeoutRuleUser::getUserId, Function.identity(), (key1, key2) -> key2));

统计List中重复数量:
Map<Integer, Long> map = userFamilyInfoList.stream().collect(Collectors.groupingBy(UserFamilyInfo::getRelation, Collectors.counting()));

根据list对象属性值去除重复值
List<Person> unique = persons.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

List<Long>去除重复值:
1. List.stream().distinct().collect(Collectors.toList());


List排序 按照从小到大排序
List<User> userList;
userList.sort((User u1, User u2) -> u1.getAge().compareTo(u2.getAge()));

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄