java8中Collectors的方法:

文章目录

  • toCollection
  • toList()
  • toSet()
  • toMap
  • joining
  • mapping/flatMapping
  • filtering
  • collectingAndThen
  • counting
  • minBy
  • maxBy
  • summingInt/summingLong/summingDouble
  • averagingInt/averagingLong/averagingDouble
  • groupingBy
  • groupingByConcurrent
  • partitioningBy
  • BinaryOperator
  • summarizingInt

toCollection

此函数返回一个收集器,它将输入元素累积到一个集合中。


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");// toCollection()
Collection<String> strCollection = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strCollection); // [a, b, c]Set<String> strSet = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet); // [a, b, c]List<String> strList1 = strList.parallelStream().sorted(String::compareToIgnoreCase).collect(Collectors.toCollection(ArrayList::new));
System.out.println(strList1); // [a, a, b, b, c]

toList()

返回一个收集器,它将输入元素累积到一个新的List中。


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");List<String> uppercaseList = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(uppercaseList); // [A, B, C, B, A]List<String> uppercaseUnmodifiableList = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toUnmodifiableList());
System.out.println(uppercaseUnmodifiableList); // [A, B, C, B, A]

toSet()


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");Set<String> uppercaseSet = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toSet());
System.out.println(uppercaseSet); // [A, B, C]Set<String> uppercaseUnmodifiableSet = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toUnmodifiableSet());
System.out.println(uppercaseUnmodifiableSet); // [A, B, C]

toMap

映射生成map

Map<String, String> map = Stream.of("a", "b", "c").collect(Collectors.toMap(Function.identity(), String::toUpperCase));
System.out.println(map); // {a=A, b=B, c=C}// Duplicate Keys will throw: Exception in thread "main"
// java.lang.IllegalStateException: Duplicate key a (attempted merging values A
// and A)
Map<String, String> mapD = Stream.of("a", "b", "c", "b", "a").collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat));
System.out.println(mapD); // {a=AA, b=BB, c=C}// above are HashMap, use below to create different types of Map
TreeMap<String, String> mapTree = Stream.of("a", "b", "c", "b").collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat, TreeMap::new));
System.out.println(mapTree); {a=A, b=BB, c=C}

joining

连接字符串


String concat = Stream.of("a", "b").collect(Collectors.joining());
System.out.println(concat); // abString csv = Stream.of("a", "b").collect(Collectors.joining(","));
System.out.println(csv); // a,bString csv1 = Stream.of("a", "b").collect(Collectors.joining(",", "[", "]"));
System.out.println(csv1); // [a,b]String csv2 = Stream.of("a", new StringBuilder("b"), new StringBuffer("c")).collect(Collectors.joining(","));
System.out.println(csv2); // a,b

mapping/flatMapping

它将Function应用于输入元素,然后将它们累积到给定的Collector


Set<String> setStr = Stream.of("a", "a", "b").collect(Collectors.mapping(String::toUpperCase, Collectors.toSet()));
System.out.println(setStr); // [A, B]Set<String> setStr1 = Stream.of("a", "a", "b").collect(Collectors.flatMapping(s -> Stream.of(s.toUpperCase()), Collectors.toSet()));
System.out.println(setStr1); // [A, B]

filtering

设置过滤条件


List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");
Set<String> set = strList2.parallelStream().collect(Collectors.filtering(s -> s.length() < 2, Collectors.toSet()));
System.out.println(set); // [1, 2]

collectingAndThen

返回一个收集器,该收集器将输入元素累积到给定的收集器中,然后执行其他完成功能

List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");List<String> unmodifiableList = strList2.parallelStream().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
System.out.println(unmodifiableList); // [1, 2, 10, 100, 20, 999]

counting

计数


Long evenCount = Stream.of(1, 2, 3, 4, 5).filter(x -> x % 2 == 0).collect(Collectors.counting());
System.out.println(evenCount); // 2

minBy

根据给定的比较器返回最小元素


Optional<Integer> min = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> x - y));
System.out.println(min); // Optional[1]

maxBy

它根据给定的比较器返回最大元素

Optional<Integer> max = Stream.of(1, 2, 3, 4, 5).collect(Collectors.maxBy((x, y) -> x - y));System.out.println(max); // Optional[5]

summingInt/summingLong/summingDouble

求总和

List<String> strList3 = Arrays.asList("1", "2", "3", "4", "5");
Integer sum = strList3.parallelStream().collect(Collectors.summingInt(Integer::parseInt));
System.out.println(sum); // 15Long sumL = Stream.of("12", "23").collect(Collectors.summingLong(Long::parseLong));
System.out.println(sumL); // 35Double sumD = Stream.of("1e2", "2e3").collect(Collectors.summingDouble(Double::parseDouble));
System.out.println(sumD); // 2100.0

averagingInt/averagingLong/averagingDouble

求平均值

List<String> strList4 = Arrays.asList("1", "2", "3", "4", "5");
Double average = strList4.parallelStream().collect(Collectors.averagingInt(Integer::parseInt));
System.out.println(average); // 3.0Double averageL = Stream.of("12", "23").collect(Collectors.averagingLong(Long::parseLong));
System.out.println(averageL); // 17.5Double averageD = Stream.of("1e2", "2e3").collect(Collectors.averagingDouble(Double::parseDouble));
System.out.println(averageD); // 1050.0

groupingBy

分组

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingBy(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

groupingByConcurrent

分组,是并发和无序的

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingByConcurrent(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

partitioningBy

返回一个Collector,它根据Predicate对输入元素进行分区,并将它们组织成Map <Boolean,List >。


Map<Boolean, List<Integer>> mapPartitionBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(x -> x % 2 == 0));
System.out.println(mapPartitionBy); // {false=[1, 3, 5, 3], true=[2, 4, 4]}

BinaryOperator

返回一个收集器,它在指定的BinaryOperator下执行其输入元素的减少。这主要用于多级缩减,例如使用groupingBy()和partitioningBy()方法指定下游收集器


Map<Boolean, Optional<Integer>> reducing = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(x -> x % 2 == 0, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Integer::intValue)))));
System.out.println(reducing); // {false=Optional[5], true=Optional[4]}

summarizingInt

返回统计数据:min, max, average, count, sum


IntSummaryStatistics summarizingInt = Stream.of("12", "23", "35").collect(Collectors.summarizingInt(Integer::parseInt));
System.out.println(summarizingInt);
//IntSummaryStatistics{count=3, sum=70, min=12, average=23.333333, max=35}

相关链接:

java8中map新增方法详解
java8中Stream的使用
java8中Collection新增方法详解
java8中Collectors的方法使用实例
java8中常用函数式接口
java8中的方法引用和构造函数引用
java8中的Collectors.groupingBy用法
java8中的Optional用法
java8中的日期和时间API

Collectors详解相关推荐

  1. Java8中Collectors详解

    文章目录 1.averagingDouble 2.collectingAndThen 3.counting 4.groupingBy 4.1groupingBy(Function) 4.2groupi ...

  2. Jdk1.8 Collectors类使用详解(实用干货)

    Collectors类大家都并不陌生,从jdk1.8开始跟stream()流配合之后,写代码效率得到提升,源码里我们可以看到有很多的方法,比如groupingBy 和maxBy,这些都是干嘛的呢,这篇 ...

  3. java11 新特性 详解

    为什么80%的码农都做不了架构师?>>>    引言: 点击-->java10 新特性 详解 点击-->java9 新特性 详解 点击-->java8 新特性 详解 ...

  4. java8新特性(四)_Stream详解

    之前写过一篇用stream处理map的文章,但是对stream没有一个整体的认识,这次结合并发编程网和ibm中介绍stream的文章进行一个总结,我会着重写对list的处理,毕竟实际工作中大家每天进行 ...

  5. Java8初体验(二)Stream语法详解(转)

    本文转自http://ifeve.com/stream/ Java8初体验(二)Stream语法详解 感谢同事[天锦]的投稿.投稿请联系 tengfei@ifeve.com 上篇文章Java8初体验( ...

  6. 聚合中返回source_Java 8 中的 Streams API 详解—— Streams 的背景以及 Java 8 中的使用详解...

    为什么需要 Stream Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 ...

  7. Java 8 Stream API详解--转

    原文地址:http://blog.csdn.net/chszs/article/details/47038607 Java 8 Stream API详解 一.Stream API介绍 Java 8引入 ...

  8. predicate java_java代码之美(13)--- Predicate详解

    Predicate详解 遇到Predicate是自己在自定义Mybatis拦截器的时候,在拦截器中我们是通过反射机制获取对象的所有属性,再查看这些属性上是否有我们自定义的UUID注解. 如果有该注解, ...

  9. JDK1.8中的Stream详解

    Stream简介 Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 XML ...

最新文章

  1. 中科院微生物所王军课题组建立靶向RNA的病原检测新方法mtNGS和mtTGS
  2. RequestMapping || @RequestMapping 模糊匹配功能
  3. “云端一体”的智能媒体生产制作演讲之路
  4. python设计一个函数定义计算并返回n价调和函数_音乐编程语言musicpy教程(第三期) musicpy的基础语法(二)...
  5. python监听键盘的库的名称_python实时监控键盘鼠标,pynput库的详细用法
  6. 查询mysql各个库和表的大小并按大小输出
  7. mysql 安装、建库、导入导出数据
  8. eclipse git拉取失败_Git(四):分支
  9. 怎么利用c 语言编程进行进制计算,编程达人 《汇编、C语言基础教程》第一章 进制1.1 进制的定义(连载)...
  10. Microsoft Office Mobile 2010 Beta 于 4 月 5 日过期
  11. 高性能MySQL(第2版)中文版pdf
  12. 修改Android序列号(Serial Number)
  13. 试验设计(DOE)方法及其关键工具
  14. Css实现雷达扫描动画效果
  15. UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xae in position解决办法
  16. 12.3 文本查询程序
  17. 用广发卡自动分期买苹果还是华为?
  18. 如何启动单线程实现多线程效果及保证安全?
  19. 3DMAX 9 角色建模3 uv展开
  20. 使用Python操作Excel图表之 为最后一个数据点添加数据标签

热门文章

  1. 跳槽必看:BAT等互联网大厂的薪资情况和职级对标!
  2. Python基础语法 序列
  3. 【C语言功法手册】第七话· 初始结构体
  4. 嵌入式系统设计学习周记①——扩展
  5. 四元数完全解析及资料汇总
  6. 魅族推荐平台架构解析(二)
  7. EasyExcel 低内存导出大数据量的Excel方案探索 50万行 50列 (附:实现代码)
  8. 计算机考试准考证的考场号看不懂
  9. 017 大数据之HBase
  10. 服务器数据库的防护策略与360后缀勒索病毒解密方法