JDK新特性——Stream代码简洁之道

2025-05-29 0 99

JDK新特性——Stream代码简洁之道

一、概述

Stream 是一组用来处理数组、集合的API,Stream API 提供了一种高效且易于使用的处理数据的方式。Java 8 中之所以费这么大的功夫引入 函数式编程 ,原因有两个:

代码简洁函数式编程写出的代码简洁且意图明确,使用stream接口让你从此告别for循环。

多核友好,Java函数式编程使得编写并行程序从未如此简单,你需要的全部就是用用一下parallel()方法

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作

二、Stream特性

1、不是数据结构,没有内部存储,不会保存数据,故每个Stream流只能使用一次 2、不支持索引访问 3、支持并行 4、很容易生成数据或集合(List,Set) 5、支持过滤、查找、转换、汇总、聚合等操作 6、延迟计算,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算

三、分类

关于应用在Stream流上的操作,可以分成两种:

  1. Intermediate(中间操作): 中间操作的返回结果都是Stream,故可以多个中间操作叠加;
  2. Terminal(终止操作): 终止操作用于返回我们最终需要的数据,只能有一个终止操作。

使用Stream流,可以清楚地知道我们要对一个数据集做何种操作,可读性强。而且可以很轻松地获取并行化Stream流,不用自己编写多线程代码,可以让我们更加专注于业务逻辑。

JDK新特性——Stream代码简洁之道

无状态: 指元素的处理不受之前元素的影响;有状态: 指该操作只有拿到所有元素之后才能继续下去。非短路操作: 指必须处理所有元素才能得到最终结果;短路操作: 指遇到某些符合条件的元素就可以得到最终结果,如 A || B,只要A为true,则无需判断B的结果。

四、Stream的创建

1、通过数组来生成 2、通过集合来生成 3、通过Stream.generate方法来创建 4、通过Stream.iterate方法来创建 5、其他Api创建

4.1 通过数组来生成

  1. //通过数组来生成
  2. staticvoidgen1(){
  3. String[]strs={"a","b","c","d"};
  4. Stream<String>strs1=Stream.of(strs);//使用Stream中的静态方法:of()
  5. strs1.forEach(System.out::println);//打印输出(a、b、c、d)
  6. }

4.2 通过集合来生成

  1. //通过集合来生成
  2. staticvoidgen2(){
  3. List<String>list=Arrays.asList("1","2","3","4");
  4. Stream<String>stream=list.stream();//获取一个顺序流
  5. stream.forEach(System.out::println);//打印输出(1,2,3,4)
  6. }

4.3 通过Stream.generate方法来创建

  1. //generate
  2. staticvoidgen3(){
  3. Stream<Integer>generate=Stream.generate(()->1);//使用Stream中的静态方法:generate()
  4. //limit返回由该流的元素组成的流,截断长度不能超过maxSize
  5. generate.limit(10).forEach(System.out::println);//打印输出(打印10个1)
  6. }

4.4 通过Stream.iterate方法来创建

  1. //使用iterator
  2. staticvoidgen4(){
  3. Stream<Integer>iterate=Stream.iterate(1,x->x+1);//使用Stream中的静态方法:iterate()
  4. iterate.limit(10).forEach(System.out::println);//打印输出(1,2,3,4,5,6,7,8,9,10)
  5. }

4.5其他Api创建

  1. //其他方式
  2. staticvoidgen5(){
  3. Stringstr="abcdefg";
  4. IntStreamstream=str.chars();//获取str字节码
  5. stream.forEach(System.out::println);//打印输出(97,98,99,100,101,102,103)
  6. }

五、Stream的常用API

5.1 中间操作

1. filter:过滤流中的某些元素

  1. //中间操作:如果调用方法之后返回的结果是Stream对象就意味着是一个中间操作
  2. Arrays.asList(1,2,3,4,5).stream()//获取顺序流
  3. .filter((x)->x%2==0)//24
  4. .forEach(System.out::println);
  5. //求出结果集中所有偶数的和
  6. intcount=Arrays.asList(1,2,3,4,5,6,7,8,9).stream()//获取顺序流
  7. .filter(x->x%2==0).//2468
  8. mapToInt(x->x).sum();//求和
  9. System.out.println(count);//打印输出20

2. distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素

  1. Arrays.asList(1,2,3,3,3,4,5,2).stream()//获取顺序流
  2. .distinct()//去重
  3. .forEach(System.out::println);//打印输出(1,2,3,4,5)
  4. System.out.println("去重:—————");
  5. Arrays.asList(1,2,3,3,3,4,5,2).stream()//获取顺序流
  6. .collect(Collectors.toSet())//Set()去重
  7. .forEach(System.out::println);//打印输出(1,2,3,4,5)

3. 排序

sorted():返回由此流的元素组成的流,根据自然顺序排序。sorted(Comparator com):返回由该流的元素组成的流,根据提供的 Comparator进行排序。

  1. //获取最大值和最小值但是不使用minmax方法
  2. List<Integer>list=Arrays.asList(1,2,3,4,5,6);
  3. Optional<Integer>min=list.stream().sorted().findFirst();//自然排序根据数字从小到大排列
  4. System.out.println(min.get());//打印输出(1)
  5. Optional<Integer>max2=list.stream().sorted((a,b)->b-a).findFirst();//定时排序根据最大数进行排序
  6. System.out.println(max2.get());//打印输出(6)
  7. //按照大小(a-z)排序
  8. Arrays.asList("java","c#","python","scala").stream().sorted().forEach(System.out::println);
  9. //按照长度排序
  10. Arrays.asList("java","c#","python","scala").stream().sorted((a,b)->a.length()-b.length()).forEach(System.out::println);

4. 截取

limit(n):返回由此流的元素组成的流,截短长度不能超过 nskip(n):在丢弃流的第n元素后,配合limit(n)可实现分页

  1. //打印20-30这样的集合数据
  2. Stream.iterate(1,x->x+1).limit(50)//limit50总共到50
  3. .skip(20)//跳过前20
  4. .limit(10)//打印10个
  5. .forEach(System.out::println);//打印输出(21,22,23,24,25,26,27,28,29,30)

5. 转换

map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

  1. List<String>list=Arrays.asList("a,b,c","1,2,3");
  2. //将每个元素转成一个新的且不带逗号的元素
  3. Stream<String>s1=list.stream().map(s->s.replaceAll(",",""));
  4. s1.forEach(System.out::println);//abc123
  5. Stream<String>s3=list.stream().flatMap(s->{
  6. //将每个元素转换成一个stream
  7. String[]split=s.split(",");
  8. Stream<String>s2=Arrays.stream(split);
  9. returns2;
  10. });
  11. s3.forEach(System.out::println);//abc123

6. 消费

peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。

  1. //将str中的每一个数值都打印出来,同时算出最终的求和结果
  2. Stringstr="11,22,33,44,55";
  3. System.out.println(Stream.of(str.split(",")).peek(System.out::println).mapToInt(Integer::valueOf).sum());//1122334455165

5.2 终止操作

1. 循环:forEach

Users类:

  1. importjava.util.Date;
  2. /**
  3. *@program:lambda
  4. *@ClassNameUsers
  5. *@description:
  6. *@author:muxiaonong
  7. *@create:2020-10-2411:00
  8. *@Version1.0
  9. **/
  10. publicclassUsers{
  11. privateStringname;
  12. publicUsers(){}
  13. /**
  14. *@paramname
  15. */
  16. publicUsers(Stringname){
  17. this.name=name;
  18. }
  19. /**
  20. *@paramname
  21. *@return
  22. */
  23. publicstaticUsersbuild(Stringname){
  24. Usersu=newUsers();
  25. u.setName(name);
  26. returnu;
  27. }
  28. publicStringgetName(){
  29. returnname;
  30. }
  31. publicvoidsetName(Stringname){
  32. this.name=name;
  33. }
  34. @Override
  35. publicStringtoString(){
  36. return"name='"+name+'\\'';
  37. }
  38. }
  1. //创建一组自定义对象
  2. Stringstr2="java,scala,python";
  3. Stream.of(str2.split(",")).map(x->newUsers(x)).forEach(System.out::println);//打印输出(name='java'name='scala'name='python'
  4. Stream.of(str2.split(",")).map(Users::new).forEach(System.out::println);//打印输出(name='java'name='scala'name='python'
  5. Stream.of(str2.split(",")).map(x->Users.build(x)).forEach(System.out::println);//打印输出(name='java'name='scala'name='python'
  6. Stream.of(str2.split(",")).map(Users::build).forEach(System.out::println);//打印输出(name='java'name='scala'name='python'

2. 计算:min、max、count、sum

min:返回流中元素最小值max:返回流中元素最大值count:返回流中元素的总个数sum:求和

  1. //求集合中的最大值
  2. List<Integer>list=Arrays.asList(1,2,3,4,5,6);
  3. Optional<Integer>max=list.stream().max((a,b)->a-b);
  4. System.out.println(max.get());//6
  5. //求集合的最小值
  6. System.out.println(list.stream().min((a,b)->a-b).get());//1
  7. //求集合的总个数
  8. System.out.println(list.stream().count());//6
  9. //求和
  10. Stringstr="11,22,33,44,55";
  11. System.out.println(Stream.of(str.split(",")).mapToInt(x->Integer.valueOf(x)).sum());
  12. System.out.println(Stream.of(str.split(",")).mapToInt(Integer::valueOf).sum());
  13. System.out.println(Stream.of(str.split(",")).map(x->Integer.valueOf(x)).mapToInt(x->x).sum());
  14. System.out.println(Stream.of(str.split(",")).map(Integer::valueOf).mapToInt(x->x).sum());

3. 匹配:anyMatch、 allMatch、 noneMatch、 findFirst、 findAny

anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回falseallMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回falsenoneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回falsefindFirst:返回流中第一个元素findAny:返回流中的任意元素

  1. List<Integer>list=Arrays.asList(1,2,3,4,5,6);
  2. System.out.println(list.stream().allMatch(x->x>=0));//如果集合中的元素大于等于0返回true
  3. System.out.println(list.stream().noneMatch(x->x>5));//如果集合中的元素有大于5的元素。返回false
  4. System.out.println(list.stream().anyMatch(x->x>4));//如果集合中有大于四4的元素,返回true
  5. //取第一个偶数
  6. Optional<Integer>first=list.stream().filter(x->x%10==6).findFirst();
  7. System.out.println(first.get());//6
  8. //任意取一个偶数
  9. Optional<Integer>any=list.stream().filter(x->x%2==0).findAny();
  10. System.out.println(any.get());//2

4.收集器:toArray、collect

collect:接收一个Collector实例,将流中元素收集成另外一个数据结构Collector

  1. Supplier supplier();创建一个结果容器A
  2. BiConsumer
  3. BinaryOperator combiner();函数接口,该参数的作用跟上一个方法(reduce)中的combiner参数一样,将并行流中各个子进程的运行结果(accumulator函数操作后的容器A)进行合并。
  4. Function
  5. Set characteristics();返回一个不可变的Set集合,用来表明该Collector的特征
  1. /**
  2. *@program:lambda
  3. *@ClassNameCustomer
  4. *@description:
  5. *@author:muxiaonong
  6. *@create:2020-10-2411:36
  7. *@Version1.0
  8. **/
  9. publicclassCustomer{
  10. privateStringname;
  11. privateIntegerage;
  12. …getset忽略
  13. }
  14. publicstaticvoidmain(String[]args){
  15. Customerc1=newCustomer("张三",10);
  16. Customerc2=newCustomer("李四",20);
  17. Customerc3=newCustomer("王五",10);
  18. List<Customer>list=Arrays.asList(c1,c2,c3);
  19. //转成list
  20. List<Integer>ageList=list.stream().map(Customer::getAge).collect(Collectors.toList());
  21. System.out.println("ageList:"+ageList);//ageList:[10,20,10]
  22. //转成set
  23. Set<Integer>ageSet=list.stream().map(Customer::getAge).collect(Collectors.toSet());
  24. System.out.println("ageSet:"+ageSet);//ageSet:[20,10]
  25. //转成map,注:key不能相同,否则报错
  26. Map<String,Integer>CustomerMap=list.stream().collect(Collectors.toMap(Customer::getName,Customer::getAge));
  27. System.out.println("CustomerMap:"+CustomerMap);//CustomerMap:{李四=20,张三=10,王五=10}
  28. //字符串分隔符连接
  29. StringjoinName=list.stream().map(Customer::getName).collect(Collectors.joining(",","(",")"));
  30. System.out.println("joinName:"+joinName);//joinName:(张三,李四,王五)
  31. //聚合操作
  32. //1.学生总数
  33. Longcount=list.stream().collect(Collectors.counting());
  34. System.out.println("count:"+count);//count:3
  35. //2.最大年龄(最小的minBy同理)
  36. IntegermaxAge=list.stream().map(Customer::getAge).collect(Collectors.maxBy(Integer::compare)).get();
  37. System.out.println("maxAge:"+maxAge);//maxAge:20
  38. //3.所有人的年龄
  39. IntegersumAge=list.stream().collect(Collectors.summingInt(Customer::getAge));
  40. System.out.println("sumAge:"+sumAge);//sumAge:40
  41. //4.平均年龄
  42. DoubleaverageAge=list.stream().collect(Collectors.averagingDouble(Customer::getAge));
  43. System.out.println("averageAge:"+averageAge);//averageAge:13.333333333333334
  44. //分组
  45. Map<Integer,List<Customer>>ageMap=list.stream().collect(Collectors.groupingBy(Customer::getAge));
  46. System.out.println("ageMap:"+ageMap);//ageMap:{20=[com.mashibing.stream.Customer@20ad9418],10=[com.mashibing.stream.Customer@31cefde0,com.mashibing.stream.Customer@439f5b3d]}
  47. //分区
  48. //分成两部分,一部分大于10岁,一部分小于等于10岁
  49. Map<Boolean,List<Customer>>partMap=list.stream().collect(Collectors.partitioningBy(v->v.getAge()>10));
  50. System.out.println("partMap:"+partMap);
  51. //规约
  52. IntegerallAge=list.stream().map(Customer::getAge).collect(Collectors.reducing(Integer::sum)).get();
  53. System.out.println("allAge:"+allAge);//allAge:40
  54. }
  1. publicstaticvoidmain(String[]args){
  2. Customerc1=newCustomer("张三",10);
  3. Customerc2=newCustomer("李四",20);
  4. Customerc3=newCustomer("王五",10);
  5. List<Customer>list=Arrays.asList(c1,c2,c3);
  6. //转成list
  7. List<Integer>ageList=list.stream().map(Customer::getAge).collect(Collectors.toList());
  8. System.out.println("ageList:"+ageList);//ageList:[10,20,10]
  9. //转成set
  10. Set<Integer>ageSet=list.stream().map(Customer::getAge).collect(Collectors.toSet());
  11. System.out.println("ageSet:"+ageSet);//ageSet:[20,10]
  12. //转成map,注:key不能相同,否则报错
  13. Map<String,Integer>CustomerMap=list.stream().collect(Collectors.toMap(Customer::getName,Customer::getAge));
  14. System.out.println("CustomerMap:"+CustomerMap);//CustomerMap:{李四=20,张三=10,王五=10}
  15. //字符串分隔符连接
  16. StringjoinName=list.stream().map(Customer::getName).collect(Collectors.joining(",","(",")"));
  17. System.out.println("joinName:"+joinName);//joinName:(张三,李四,王五)
  18. //聚合操作
  19. //1.学生总数
  20. Longcount=list.stream().collect(Collectors.counting());
  21. System.out.println("count:"+count);//count:3
  22. //2.最大年龄(最小的minBy同理)
  23. IntegermaxAge=list.stream().map(Customer::getAge).collect(Collectors.maxBy(Integer::compare)).get();
  24. System.out.println("maxAge:"+maxAge);//maxAge:20
  25. //3.所有人的年龄
  26. IntegersumAge=list.stream().collect(Collectors.summingInt(Customer::getAge));
  27. System.out.println("sumAge:"+sumAge);//sumAge:40
  28. //4.平均年龄
  29. DoubleaverageAge=list.stream().collect(Collectors.averagingDouble(Customer::getAge));
  30. System.out.println("averageAge:"+averageAge);//averageAge:13.333333333333334
  31. //分组
  32. Map<Integer,List<Customer>>ageMap=list.stream().collect(Collectors.groupingBy(Customer::getAge));
  33. System.out.println("ageMap:"+ageMap);//ageMap:{20=[com.mashibing.stream.Customer@20ad9418],10=[com.mashibing.stream.Customer@31cefde0,com.mashibing.stream.Customer@439f5b3d]}
  34. //分区
  35. //分成两部分,一部分大于10岁,一部分小于等于10岁
  36. Map<Boolean,List<Customer>>partMap=list.stream().collect(Collectors.partitioningBy(v->v.getAge()>10));
  37. System.out.println("partMap:"+partMap);
  38. //规约
  39. IntegerallAge=list.stream().map(Customer::getAge).collect(Collectors.reducing(Integer::sum)).get();
  40. System.out.println("allAge:"+allAge);//allAge:40
  41. }

六、Stream的方法摘要

修饰符和类型 方法和说明
staticCollector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的双值函数的算术平均值。
staticCollector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的整数值函数的算术平均值。
staticCollector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的长值函数的算术平均值。
static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) 适应 Collector进行额外的整理转换。
staticCollector<T,?,Long> counting() 返回 Collector类型的接受元件 T计数输入元件的数量。
static <T,K> Collector<T,?,Map<K,List>> groupingBy(Function<? super T,? extends K> classifier) 返回 Collector “由基团”上的类型的输入元件操作实现 T ,根据分类功能分组元素,并且在返回的结果 Map 。
static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream) 返回 Collector “由基团”上的类型的输入元件操作实现级联 T ,根据分类功能分组元素,然后使用下游的指定执行与给定键相关联的值的归约运算 Collector 。
static <T,K,D,A,M extends Map<K,D>>Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier, SuppliermapFactory, Collector<? super T,A,D> downstream) 返回 Collector “由基团”上的类型的输入元件操作实现级联 T ,根据分类功能分组元素,然后使用下游的指定执行与给定键相关联的值的归约运算 Collector 。
static <T,K> Collector<T,?,ConcurrentMap<K,List>> groupingByConcurrent(Function<? super T,? extends K> classifier) 返回一个并发 Collector “由基团”上的类型的输入元件操作实现 T ,根据分类功能分组元素。
static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>> groupingByConcurrent(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream) 返回一个并发 Collector “由基团”上的类型的输入元件操作实现级联 T ,根据分类功能分组元素,然后使用下游的指定执行与给定键相关联的值的归约运算 Collector 。
static <T,K,A,D,M extends ConcurrentMap<K,D>> Collector<T,?,M> groupingByConcurrent(Function<? super T,? extends K> classifier, SuppliermapFactory, Collector<? super T,A,D> downstream) 返回一个并发 Collector “由基团”上的类型的输入元件操作实现级联 T ,根据分类功能分组元素,然后使用下游的指定执行与给定键相关联的值的归约运算 Collector 。
static Collector<CharSequence,?,String> joining() 返回一个 Collector ,按照遇到的顺序将输入元素连接到一个 String中。
static Collector<CharSequence,?,String> joining(CharSequence delimiter) 返回一个 Collector ,按照遇到的顺序连接由指定的分隔符分隔的输入元素。
static Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) 返回一个 Collector ,它将按照指定的 Collector分隔的输入元素与指定的前缀和后缀进行连接。
static <T,U,A,R> Collector<T,?,R> mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream) 适应一个 Collector类型的接受元件 U至类型的一个接受元件 T通过积累前应用映射函数到每个输入元素。
staticCollector<T,?,Optional> maxBy(Comparator<? super T> comparator) 返回一个 Collector ,它根据给出的 Comparator产生最大元素,描述为 Optional。
staticCollector<T,?,Optional> minBy(Comparator<? super T> comparator) 返回一个 Collector ,根据给出的 Comparator产生最小元素,描述为 Optional。
staticCollector<T,?,Map<Boolean,List>> partitioningBy(Predicate<? super T> predicate) 返回一个 Collector ,根据Predicate对输入元素进行 Predicate ,并将它们组织成 Map<Boolean, List> 。
static <T,D,A> Collector<T,?,Map<Boolean,D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream) 返回一个 Collector ,它根据Predicate对输入元素进行 Predicate ,根据另一个 Collector减少每个分区的值,并将其组织成 Map<Boolean, D> ,其值是下游缩减的结果。
staticCollector<T,?,Optional> reducing(BinaryOperatorop) 返回一个 Collector ,它在指定的 Collector下执行其输入元素的 BinaryOperator 。
staticCollector<T,?,T> reducing(T identity, BinaryOperatorop) 返回 Collector执行下一个指定的减少其输入元件的 BinaryOperator使用所提供的身份。
static <T,U> Collector<T,?,U> reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperatorop) 返回一个 Collector ,它在指定的映射函数和 BinaryOperator下执行其输入元素的 BinaryOperator 。
staticCollector<T,?,DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper) 返回一个 Collector , double生产映射函数应用于每个输入元素,并返回结果值的汇总统计信息。
staticCollector<T,?,IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper) 返回一个 Collector , int生产映射函数应用于每个输入元素,并返回结果值的汇总统计信息。
staticCollector<T,?,LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper) 返回一个 Collector , long生产映射函数应用于每个输入元素,并返回结果值的汇总统计信息。
staticCollector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的双值函数的和。
staticCollector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的整数值函数的和。
staticCollector<T,?,Long> summingLong(ToLongFunction<? super T> mapper) 返回一个 Collector ,它产生应用于输入元素的长值函数的和。
static <T,C extends Collection> Collector<T,?,C> toCollection(SuppliercollectionFactory) 返回一个 Collector ,按照遇到的顺序将输入元素累加到一个新的 Collection中。
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) 返回一个并发的 Collector ,它将元素累加到 ConcurrentMap ,其键和值是将所提供的映射函数应用于输入元素的结果。
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperatormergeFunction) 返回一个并发的 Collector ,它将元素累加到一个 ConcurrentMap ,其键和值是将提供的映射函数应用于输入元素的结果。
static <T,K,U,M extends ConcurrentMap<K,U>> Collector<T,?,M> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperatormergeFunction, SuppliermapSupplier) 返回一个并发的 Collector ,它将元素累加到一个 ConcurrentMap ,其键和值是将所提供的映射函数应用于输入元素的结果。
staticCollector<T,?,List> toList() 返回一个 Collector ,它将输入元素 List到一个新的 List 。
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) 返回一个 Collector ,它将元素累加到一个 Map ,其键和值是将所提供的映射函数应用于输入元素的结果。
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperatormergeFunction) 返回一个 Collector ,它将元素累加到 Map ,其键和值是将提供的映射函数应用于输入元素的结果。
static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperatormergeFunction, SuppliermapSupplier) 返回一个 Collector ,它将元素累加到一个 Map ,其键和值是将所提供的映射函数应用于输入元素的结果。
staticCollector<T,?,Set> toSet() 返回一个 Collector ,将输入元素 Set到一个新的 Set 。

七、总结

对于Java中新特性除了 Stream 还有lamaba表达式都是可以帮忙我们很好的去优化代码,使我们的代码简洁且意图明确,避免繁琐的重复性的操作,对于文中有兴趣的小伙伴可以操作起来,又不懂的小伙伴可以在下面进行留言,小农看到了会第一时间回复大家,谢谢,大家加油!

原文地址:https://mp.weixin.qq.com/s/LuV5QGSfP60EPWBTeY3SuQ

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 JDK新特性——Stream代码简洁之道 https://www.kuaiidc.com/111567.html

相关文章

发表评论
暂无评论