- 集合中抽取某一元素的集合
java
// 抽取一个字段成为新的组合
List<String> list = userService.stream().map(User::getCreateId()).collect(Collectors.toList());
// map形式的抽取
List<String> list = userService.stream().map(e -> e.get("name")).collect(Collectors.toList());
- 集合去重
java
//根据单个字段去重
List<Product> list = ProductService.list(new Product().setCreateUserId(nodeUser.getUserId())).stream().distinct().collect(Collectors.toList());
//根据多个字段去重 (id和年份 两字段去重)
List<GoalDetail> goList = goLists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(goal -> go.getGoId()+";"+goal.getGoYear()))), ArrayList::new));
//简单字符串集合去重
List<String> list = Arrays.asList("111","222","333");
list.stream().distinct().forEach(System.out::println);
- 集合中抽取2个字段组成Map
java
// 取出的多个字段组成的map格式
Map<String, Integer> subejctMap = subjectList.stream().collect(Collectors.toMap(Subject::getName, Subject::getClockNumber));
- 筛选条件利用 filter设置相关条件得到相应的集合
java
// 从人员列表中抽取性别为男生集合
List<User> manList = users.stream().filter(a -> a.getSex().equals(CommonConstants.ONE)).collect(Collectors.toList());
// 从map中抽取name不为空的集合
list.stream().filter((Map<String,Object>a) -> StringUtils.isNotBlank(a.get("name"))).collect(Collectors.toList())
- 集合排序
java
// 此为对list进行排序,先正序后加上.reversed()进行倒序排列,不加则为正序
List<SysDept> depts = deptList.stream().sorted(Comparator.comparing(Dept::getOrder).reversed()).collect(Collectors.toList());
// 直接进行倒序排列
List<SysDept> depts = deptList.stream().sorted(Comparator.comparing(Dept::getOrder, Comparator.reverseOrder())).collect(Collectors.toList());
// 多字段排序
List<SysDept> depts = deptList.stream().sorted(Comparator.comparing(Dept::getOrder, Comparator.reverseOrder().thenComparing(Dept::getId))).collect(Collectors.toList());
// 排序后抽取其中一个字段来组成新的集合
List<String> valueList = resultList.stream().sorted(Comparator.comparing((Map<String, Object> e) -> (BigDecimal) e.get("amount")).reversed()).map(e -> String.valueOf(e.get("value"))).collect(Collectors.toList());
//简单字符串集合排序
List<String> list = Arrays.asList("111","222","333");
list.stream().sorted().forEach(System.out::println);
- 集合中某一字段相加求和
java
// BigDecimal的分数一列的值求和
BigDecimal intotalSorce = scorelist.stream().map(ScoreRecord::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
// Inteter的分数一列的值求和
Integer allSum = list.stream().mapToInt(e -> StringUtils.isNotBlank(e.getLevel()) ? Integer.parseInt(e.getLevel()) : 0).sum();
// map中的BigDecimal 元素求和
BigDecimal totalNumber = list.stream().map(map -> JSONObject.parseObject(JSON.toJSONString(map)).getBigDecimal("number")).reduce(BigDecimal::add).get();
// map中的Integer 元素求和
Integer typeCount = list.stream().collect(Collectors.summingInt(map -> JSONObject.parseObject(JSON.toJSONString(map)).getInteger("typeCount")));