
本文共 2601 字,大约阅读时间需要 8 分钟。
1. list 转数组
String[] ss = listStr.stream().toArray(String[]::new);
2. 删除 list 中所有null
List<Integer> listWithoutNulls = list.stream() .filter(Objects::nonNull) .collect(Collectors.toList());
List<Integer> listWithoutNulls = list.parallelStream() .filter(Objects::nonNull) .collect(Collectors.toList());
3.将list 中实体类两个字段转 map
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));
4.求和 list 中对象
1. BigDecimal allFullMarketPrice = entityList.stream().filter(value -> value.getFullMarketPrice()!=null).map(SceneAnalysisRespVo::getFullMarketPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
2 . BigDecimal total = naturalDayList.stream().reduce(BigDecimal.ZERO, BigDecimal::add); 其中:naturalDayList 是list 对象
5.分组函数
Map<String, List<Object>> groupMap = list.stream().collect(Collectors.groupingBy(Object::getVmName));
6. 大数据量的list 分批次 切割处理
按每n个一组分割
private static final Integer MAX_NUMBER = n ;
/* 计算切分次数 */
private static Integer countStep(Integer size) { return (size + MAX_NUMBER - 1) / MAX_NUMBER; }
int limit = countStep(list.size());
//方法一:使用流遍历操作
List<List<Object>> mglist = new ArrayList<>();
Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> { mglist.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList())); });
//方法二 :获取分割后的集合
List<List<T>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a *MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());
7. String 转 list
Arrays.stream(strArr.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
8. list 转string ....
List<String> list2 = Arrays.asList("文学","小说","历史","言情","科幻","悬疑");
list2.stream().collect(Collectors.joining("-"));
String string= "文学-小说-历史-言情-科幻-悬疑";
List<String> list = Arrays.asList(string.split("-")).stream().map(s -> String.format(s.trim())).collect(Collectors.toList());9. 利用lambda 去重
List<String> dataList = list.stream().distinct().collect(Collectors.toList()); //字符串去重
personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)); // 对象属性去重
10.多个统一对象的list 合成一个list 集合
List<StatisResp> list = new ArrayList<>();
statisResps.parallelStream().filter(v -> v.getStaffName() != null).collect(Collectors.groupingBy(o -> (o.getServiceStaffId()),Collectors.toList())).forEach( (id,transfer) ->{ transfer.stream().reduce((a,b) -> new StatisResp(a.getServiceStaffId(),a.getStaffName(),a.getDayCount()+b.getDayCount())).ifPresent(list::add); });
发表评论
最新留言
关于作者
