前言
项目中经常会使用Stream操作一些集合数据,今天记录一下我经常使用的Stream操作
求和操作
public static void main(String[] args) { List<User> users = generateUserList();int reduce = users.stream().mapToInt(x -> x.getSalary().intValue()).reduce(0, Integer::sum); log.info("Int sum - {}", reduce); BigDecimal reduce1 = users.stream().map(User::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add); log.info("BigDecimal sum - {}", reduce); }private static List<User> generateUserList() { List<User> users = new ArrayList<>();for (int i = 0; i < 5; i++) { users.add(new User((long) (i + 1), StrFormatter.format("用户-{}", i), RandomUtil.randomBigDecimal(new BigDecimal(1000), new BigDecimal(100000)))); }return users; }复制代码
结果:
16:03:32.966 [main] INFO com.springboot.example.stream.StreamTest - Int sum - 31128616:03:32.977 [main] INFO com.springboot.example.stream.StreamTest - BigDecimal sum - 311286复制代码
这里使用了Integer 及BigDecimal类型的求和,其他的例如Long Double类型的自行尝试,操作都是一样的。
分组操作
Map<String, List<User>> groups = users.stream().collect(Collectors.groupingBy(User::getName, Collectors.toList()));复制代码
结果
16:19:24.018 [main] INFO com.springboot.example.stream.StreamTest - groups - {"用户-0":[{"name":"用户-0","id":1,"salary":44133.974869422615}],"用户-1":[{"name":"用户-1","id":2,"salary":32433.52878974182}],"用户-4":[{"name":"用户-4","id":5,"salary":26726.1799749091}],"用户-2":[{"name":"用户-2","id":3,"salary":83274.99312309967}],"用户-3":[{"name":"用户-3","id":4,"salary":1579.9248811900475}]}复制代码
自定义分组的数据结构
List<Object> groupCustomize = users.stream().collect(Collectors.groupingBy(User::getName, Collectors.toList())).entrySet().stream().map(e -> { Map<String, Object> newObj = new HashMap<>(); newObj.put("name", e.getKey()); newObj.put("items", e.getValue());return newObj; }).collect(Collectors.toList());复制代码
结果
16:24:23.554 [main] INFO com.springboot.example.stream.StreamTest - groups customize - [{"name":"用户-0","items":[{"name":"用户-0","id":1,"salary":69329.43639757435}]},{"name":"用户-1","items":[{"name":"用户-1","id":2,"salary":14632.879595342842}]},{"name":"用户-4","items":[{"name":"用户-4","id":5,"salary":52953.301688394306}]},{"name":"用户-2","items":[{"name":"用户-2","id":3,"salary":29500.813638173757}]},{"name":"用户-3","items":[{"name":"用户-3","id":4,"salary":30750.353923258994}]}]复制代码