提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
java8 stream提供了常规操作,可以简化编程,提高效率,我把自己常用的例子归纳下来
代码示例
代码如下(示例):
//list字符串逗号拼接
String str=strList.stream().collect(Collectors.joining(","));
//list按照属性过滤
List<User> first = users.stream().filter(e -> e.getLevel().equals("1")).collect(Collectors.toList());
//list过滤指定属性
List<Long> ids = userlist.stream().map(e -> e.getId()).collect(Collectors.toList());
//list属性求和
BigDecimal partListPrice = list.stream().filter(e -> e.getPrice() != null).map(PartRepository::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//list属性分组
Map<Long, List<User>>=.stream().collect(Collectors.groupingBy(User::getAge));
//去重
List<String> codes = strList.stream().distinct().collect(Collectors.toList());
//list分组
Map<Long, Catalog> catalogMap = catalogList.stream().collect(Collectors.toMap(Catalog::getId, Catalog -> Catalog));
//list转map
Map<String, Long> returnListMap = orderlist.stream().collect(Collectors.toMap(Order::getDate, Order::getTotal));
//查询第一个
NetworkClient first = networkClientList.stream().findFirst().orElse(null);
if (first!=null) {
}
//排序并取top
List<BusContainer> =busContainerList.stream().sorted(Comparator.comparing(BusContainer::getEnterTime)).limit(10).collect(Collectors.toList());
//排除
if (CollectionUtils.isNotEmpty(extIds)) {
busContainerList.removeIf(item -> extIds.contains(item.getId()));
}
//计数
long iosfc= orderList.stream().count();
//求和
long iosAmount = orderList.stream().mapToLong(o->o.getMoney()).sum();