大家都在看的人 工 智 能,通俗易懂,简单易解,风趣幽默。

一:简介

Stream中有两个个方法collect和collectingAndThen用于对流中的数据进行处理,可以对流中的数据进行聚合操作,如:

  • 将流中的数据转成集合类型: toList、toSet、toMap、toCollection
  • 将流中的数据(字符串)使用分隔符拼接在一起:joining
  • 对流中的数据求最大值maxBy、最小值minBy、求和summingInt、求平均值averagingDouble
  • 对流中的数据进行映射处理 mapping
  • 对流中的数据分组:groupingBy、partitioningBy
  • 对流中的数据累计计算:reducing
<R, A> R collect(Collector<? super T, A, R> collector); // collectingAndThen : 将流中的数据通过Collector计算,最终的结果在通过Function再最终处理一下
public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher);

Collectors

public final class Collectors {// 转换成集合public static <T> Collector<T, ?, List<T>> toList();public static <T> Collector<T, ?, Set<T>> toSet();public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper);public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory);// 拼接字符串,有多个重载方法                                  public static Collector<CharSequence, ?, String> joining(CharSequence delimiter);   public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,CharSequence prefix,CharSequence suffix);      // 最大值、最小值、求和、平均值                                                         public static <T> Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator);public static <T> Collector<T, ?, Optional<T>> minBy(Comparator<? super T> comparator);public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper);      public static <T> Collector<T, ?, Double> averagingDouble(ToDoubleFunction<? super T> mapper);                   // 分组:可以分成true和false两组,也可以根据字段分成多组                                 public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier);// 只能分成true和false两组public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate);// 映射public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,Collector<? super U, A, R> downstream);public static <T, U> Collector<T, ?, U> reducing(U identity,Function<? super T, ? extends U> mapper,BinaryOperator<U> op);
}

二:示例

流转换成集合

@Test
public void testToCollection(){List<Integer> list = Arrays.asList(1, 2, 3);// [10, 20, 30]List<Integer> collect = list.stream().map(i -> i * 10).collect(Collectors.toList());// [20, 10, 30]Set<Integer> collect1 = list.stream().map(i -> i * 10).collect(Collectors.toSet());// {key1=value:10, key2=value:20, key3=value:30}Map<String, String> collect2 = list.stream().map(i -> i * 10).collect(Collectors.toMap(key -> "key" + key/10, value -> "value:" + value));// [1, 3, 4]TreeSet<Integer> collect3= Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new));
}
@Data
@ToString
@AllArgsConstructor
@RequiredArgsConstructor
public class User {private Long id;private String username;
}@Test
public void testToMap() {List<User> userList = Arrays.asList(new User(1L, "mengday"),new User(2L, "mengdee"),new User(3L, "mengdy"));// toMap 可用于将List转为Map,便于通过key快速查找到某个valueMap<Long, User> userIdAndModelMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));User user = userIdAndModelMap.get(1L);// User(id=1, username=mengday)System.out.println(user);Map<Long, String> userIdAndUsernameMap = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername));String username = userIdAndUsernameMap.get(1L);// mengdaySystem.out.println(username);
}

集合元素拼接

@Test
public void testJoining(){// a,b,cList<String> list2 = Arrays.asList("a", "b", "c");String result = list2.stream().collect(Collectors.joining(","));// Collectors.joining(",")的结果是:a,b,c  然后再将结果 x + "d"操作, 最终返回a,b,cdString str= Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"));
}

元素聚合


@Test
public void test(){// 求最值 3List<Integer> list = Arrays.asList(1, 2, 3);Integer maxValue = list.stream().collect(Collectors.collectingAndThen(Collectors.maxBy((a, b) -> a - b), Optional::get));// 最小值 1Integer minValue = list.stream().collect(Collectors.collectingAndThen(Collectors.minBy((a, b) -> a - b), Optional::get));// 求和 6Integer sumValue = list.stream().collect(Collectors.summingInt(item -> item));// 平均值 2.0Double avg = list.stream().collect(Collectors.averagingDouble(x -> x));
}
@Test
public void test(){// 映射:先对集合中的元素进行映射,然后再对映射的结果使用Collectors操作// A,B,CStream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(",")));
}

分组


public class User {private Long id;private String username;private Integer type;// Getter & Setter & toString
}@Test
public void testGroupBy(){List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);// 奇偶数分组:奇数分一组,偶数分一组// groupingBy(Function<? super T, ? extends K> classifier) 参数是Function类型,Function返回值可以是要分组的条件,也可以是要分组的字段// 返回的结果是Map,其中key的数据类型为Function体中计算类型,value是List<T>类型,为分组的结果Map<Boolean, List<Integer>> result = list.stream().collect(Collectors.groupingBy(item -> item % 2 == 0));// {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]}System.out.println(result);// partitioningBy 用于分成两组的情况Map<Boolean, List<Integer>> twoPartiton = list.stream().collect(Collectors.partitioningBy(item -> item % 2 == 0));System.out.println(twoPartiton);User user = new User(1L, "zhangsan", 1);User user2 = new User(2L, "lisi", 2);User user3 = new User(3L, "wangwu", 3);User user4 = new User(4L, "fengliu", 1);List<User> users = Arrays.asList(user, user2, user3, user4);// 根据某个字段进行分组Map<Integer, List<User>> userGroup = users.stream().collect(Collectors.groupingBy(item -> item.type));/*** key 为要分组的字段* value 分组的结果* {*  1=[User{id=1, username='zhangsan', type=1}, User{id=4, username='fengliu', type=1}],*  2=[User{id=2, username='lisi', type=2}],*  3=[User{id=3, username='wangwu', type=3}]* }*/System.out.println(userGroup);
}    // 分组并对分组中的数据统计
@Test
public void testGroupBy2() {Foo foo1 = new Foo(1, 2);Foo foo2 = new Foo(2, 23);Foo foo3 = new Foo(2, 6);List<Foo> list = new ArrayList<>(4);list.add(foo1);list.add(foo2);list.add(foo3);Map<Integer, IntSummaryStatistics> collect = list.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount)));IntSummaryStatistics statistics1 = collect.get(1);IntSummaryStatistics statistics2 = collect.get(2);System.out.println(statistics1.getSum());System.out.println(statistics1.getAverage());System.out.println(statistics1.getMax());System.out.println(statistics1.getMin());System.out.println(statistics1.getCount());System.out.println(statistics2.getSum());System.out.println(statistics2.getAverage());System.out.println(statistics2.getMax());System.out.println(statistics2.getMin());System.out.println(statistics2.getCount());
}

累计操作

@Test
public void testReducing(){// sum: 是每次累计计算的结果,b是Function的结果System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (sum, b) -> {System.out.println(sum + "-" + b);return sum + b;})));// 下面代码是对reducing函数功能实现的描述,用于理解reducing的功能int sum = 0;List<Integer> list3 = Arrays.asList(1, 3, 4);for (Integer item : list3) {int b = item + 1;System.out.println(sum + "-" + b);sum = sum + b;}System.out.println(sum);// 注意reducing可以用于更复杂的累计计算,加减乘除或者更复杂的操作// result = 2 * 4 * 5 = 40System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(1, x -> x + 1, (result, b) -> {System.out.println(result + "-" + b);return result * b;})));
}

对BigDecimal分组求和。

Map<String, BigDecimal> returnPaymentMap = retrnPayments.stream().collect(Collectors.groupingBy(Payment::getPayType,Collectors.mapping(Payment::getPayAmount,Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

分享一个朋友的人工智能教程。比较通俗易懂,风趣幽默,感兴趣的朋友可以去看看。

JDK1.8新特性(五): Collectors相关推荐

  1. jdk1.8新特性(五)——Stream

    转载自:https://mp.weixin.qq.com/s/adKZrOe6nFEmuADHijsAtA 在Java中,集合和数组是我们经常会用到的数据结构,需要经常对他们做增.删.改.查.聚合.统 ...

  2. JDK1.8 新特性(全)

    JDK1.8 新特性 本文主要介绍了JDK1.8版本中的一些新特性,乃作者视频观后笔记,仅供参考. jdk1.8新特性知识点: Lambda表达式 函数式接口 方法引用和构造器调用 Stream AP ...

  3. jdk1.8新特性的应用-Stream 的终止操作

    jdk1.8新特性的应用-Stream 的终止操作 public class TestStreamApi4 {List<Employee> emps = Arrays.asList(new ...

  4. java 1.7 可变参数,JDK1.7新特性(2):异常和可变长参数处理

    异常 jdk1.7对try--catch--finally的异常处理模式进行了增强,下面我们依次来看增强的方面. 1. 为了防止异常覆盖,给Throwable类增加了addSuppressed方法,可 ...

  5. 黑马程序员————高新技术————JDK1.5新特性

    ----------------------ASP.Net+Android+IOS开发----------------------期待与您交流! JDK1.5新特性 一:静态导入 l  Import语 ...

  6. java基础知识总结:基础知识、面向对象、集合框架、多线程、jdk1.5新特性、IO流、网络编程

    目录 一.基础知识: 二.面向对象 三.集合框架 四.多线程: 五.jdk1.5的新特性 六.IO流 七.网络编程: 一.基础知识: 1.JVM.JRE和JDK的区别: JVM(Java Virtua ...

  7. JDK12的新特性:teeing collectors

    文章目录 简介 talk is cheap, show me the code Teeing方法深度剖析 Characteristics 总结 JDK12的新特性:teeing collectors ...

  8. jdk1.8新特性_Lambda表达式的引入

    jdk1.8新特性_Lambda表达式的引入 引入 需求: 获取工资大于20000的员工信息 public class Employee {private String name;private in ...

  9. jdk1.5新特性5之枚举之模拟枚举类型

    一 简单应用 package cn.xy.Enum; public enum TrafficLamp {  RED,GREEN,YELLOW; } TrafficLamp red = TrafficL ...

最新文章

  1. Nat. Biotech.|药物设计的AI生成模型
  2. sqlyog连接服务出现的2003和1130错误问题
  3. 【译】Diving Into The Ethereum VM Part 2 — How I Learned To Start Worrying And Count The Storage Cost
  4. CVPR 2017 ADNet:《 Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning》论文笔记
  5. java水印图片,Java添加水印+图片水印+文字水印
  6. VS2010 Visual Assist X 的配合
  7. IDA64 Fatal error before kernel init
  8. 指针常量与常量指针精解【一次掌握】
  9. BugkuCTF-WEB题GET和POST
  10. OJ1084: 计算两点间的距离(多实例测试)(C语言)
  11. throw在try中抛出异常,然后用catch捕捉并处理这个异常,同时catch也可以再次抛出这个异常...
  12. java.lang.IllegalStateException: Max number of active transactions reached:50
  13. 思维导图 · App的商业模式:如何寻找商业化
  14. 投资回报率模版_投资回报率已死!
  15. python乒乓球比赛规则介绍_乒乓球比赛详细规则
  16. python3 经典练习题:输入三个数,输出三个数中的最大数
  17. 一个能启动电脑的U盘
  18. 逻辑对计算机,对计算机模拟中的逻辑、方法论的几点认识
  19. 浏览器原理及HTTP网络协议基础简答题
  20. 如何成为一名全栈工程师:专业建议与技能要求

热门文章

  1. 2019苏州计算机一级考试时间,2019年3月苏州科技大学计算机等级考试3月9日-10日...
  2. bash 与 csh 区别
  3. 基于Snappy实现数据压缩和解压
  4. 护眼台灯哪个品牌更好?2022年最值得入手的护眼台灯
  5. iOS面霸计划(难度)
  6. 直流有刷电机开环调速基于STM32F302R8+X-NUCLEO-IHM07M1(一)
  7. tkyte.blogs
  8. centos 7 YUM 安装LAMP 环境
  9. 转:Win10秘笈:两种方式修改网卡物理地址(MAC)
  10. OS_exp2 进程控制(Linux环境)