1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Set;
  4. import java.util.function.BiConsumer;
  5. import java.util.function.BinaryOperator;
  6. import java.util.function.Function;
  7. import java.util.function.Supplier;
  8. import java.util.stream.Collector;
  9.  
  10. public class MyListCollector<T> implements Collector<T, List<T>, List<T>>{
  11.  
  12. @Override
  13. public Supplier<List<T>> supplier() {
  14. return ArrayList<T>::new;
  15. }
  16.  
  17. @Override
  18. public BiConsumer<List<T>, T> accumulator() {
  19. // return ArrayList<T>::add;
  20. return List::add;
  21. }
  22.  
  23. @Override
  24. public BinaryOperator<List<T>> combiner() {
  25. return null;
  26. }
  27.  
  28. @Override
  29. public Function<List<T>, List<T>> finisher() {
  30. return null;
  31. }
  32.  
  33. @Override
  34. public Set<Characteristics> characteristics() {
  35. return null;
  36. }
  37. }
  1. import java.util.Arrays;
  2. import java.util.Collections;
  3. import java.util.EnumSet;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7. import java.util.function.BiConsumer;
  8. import java.util.function.BinaryOperator;
  9. import java.util.function.Function;
  10. import java.util.function.Supplier;
  11. import java.util.stream.Collector;
  12.  
  13. import static java.util.stream.Collector.Characteristics.CONCURRENT;
  14. import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;
  15. import static java.util.stream.Collector.Characteristics.UNORDERED;
  16.  
  17. public class MySetCollector<T> implements Collector<T, Set<T>, Set<T>> {
  18.  
  19. @Override
  20. public Supplier<Set<T>> supplier() {
  21. System.out.println("supplier");
  22. return HashSet<T>::new;
  23. }
  24.  
  25. // 如果return HashSet<T>::add,那么会编译报错,原因在于
  26. // 如果这里return的是HashSet,而supplier方法返回的是TreeSet
  27. // 那么显然,中间用于累积的容器的类型二者是不一致的;就会出现问题
  28. // 如果这里使用了Set::add,即接口类型,那么它就会兼容于supplier
  29. // 所返回的容器类型
  30. // 总之:这里return的类型必须要与泛型的类型保持完全一致
  31. @Override
  32. public BiConsumer<Set<T>, T> accumulator() {
  33. System.out.println("accumulator");
  34. // return Set<T>::add;
  35.  
  36. return (set, item) -> {
  37. System.out.println(item + ", " + set + ", " + Thread.currentThread().getName() );
  38. set.add(item);
  39. };
  40. }
  41.  
  42. @Override
  43. public BinaryOperator<Set<T>> combiner() {
  44. System.out.println("combiner");
  45.  
  46. return (set1, set2) -> {
  47. set1.addAll(set2);
  48. return set1;
  49. };
  50. }
  51.  
  52. @Override
  53. public Function<Set<T>, Set<T>> finisher() {
  54. System.out.println("finisher");
  55.  
  56. return Function.identity();
  57.  
  58. // 对于IDENTITY_FINISH来说,该方法可以直接抛出异常,该方法实际上并不会被调用
  59. // throw new UnsupportedOperationException();
  60. }
  61.  
  62. // 该方法会被调用2次,分别用于确定UNORDERED与IDENTITY_FINISH
  63. @Override
  64. public Set<Characteristics> characteristics() {
  65. System.out.println("characteristics");
  66.  
  67. return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH, CONCURRENT, UNORDERED));
  68. }
  69.  
  70. public static void main(String[] args) {
  71. List<String> list = Arrays.asList("hello", "world", "welcome", "hello", "a", "b", "c", "d", "e", "f", "g", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii");
  72. Set<String> preSet = new HashSet<>();
  73. preSet.addAll(list);
  74.  
  75. System.out.println(preSet);
  76.  
  77. Set<String> set = preSet.stream().parallel().collect(new MySetCollector<>());
  78.  
  79. System.out.println("---------------");
  80.  
  81. System.out.println(set);
  82.  
  83. // System.out.println(Runtime.getRuntime().availableProcessors());
  84. }
  85. }
  1. import java.util.Arrays;
  2. import java.util.Collections;
  3. import java.util.EnumSet;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.TreeMap;
  9. import java.util.function.BiConsumer;
  10. import java.util.function.BinaryOperator;
  11. import java.util.function.Function;
  12. import java.util.function.Supplier;
  13. import java.util.stream.Collector;
  14.  
  15. public class MySetCollector2<T> implements Collector<T, Set<T>, Map<T, T>> {
  16.  
  17. @Override
  18. public Supplier<Set<T>> supplier() {
  19. System.out.println("supplier invoked!");
  20.  
  21. // 串行流调用时,只会生成一个HashSet
  22. // 并行流调用时,每个线程都会生成一个HashSet
  23. /**
  24. * * A a1 = supplier.get();
  25. * accumulator.accept(a1, t1);
  26. * accumulator.accept(a1, t2);
  27. * R r1 = finisher.apply(a1); // result without splitting
  28. *
  29. * A a2 = supplier.get();
  30. * accumulator.accept(a2, t1);
  31. * A a3 = supplier.get();
  32. * accumulator.accept(a3, t2);
  33. * R r2 = finisher.apply(combiner.apply(a2, a3)); // result with splitting
  34. */
  35.  
  36. return () -> {
  37. System.out.println("~~~~~~~~~~~~~~~~~");
  38. return new HashSet<T>();
  39. };
  40.  
  41. // return HashSet<T>::new;
  42. }
  43.  
  44. @Override
  45. public BiConsumer<Set<T>, T> accumulator() {
  46. System.out.println("accumulator invoked!");
  47.  
  48. return (set, item) -> {
  49. System.out.println("accumulator, " + set + ", " + Thread.currentThread().getName());
  50. set.add(item);
  51. };
  52. }
  53.  
  54. @Override
  55. public BinaryOperator<Set<T>> combiner() {
  56. System.out.println("combiner invoked!");
  57.  
  58. return (set1, set2) -> {
  59. System.out.println("combiner, " + set1 + ", " + set2);
  60. set1.addAll(set2);
  61. return set1;
  62. };
  63. }
  64.  
  65. @Override
  66. public Function<Set<T>, Map<T, T>> finisher() {
  67. System.out.println("finisher invoked!");
  68.  
  69. return set -> {
  70. System.out.println("finisher, " + set);
  71. Map<T, T> map = new TreeMap<>();
  72. set.stream().forEach(item -> map.put(item, item));
  73. return map;
  74. };
  75. }
  76.  
  77. @Override
  78. public Set<Characteristics> characteristics() {
  79. System.out.println("characteristics invoked!");
  80. // return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED, Characteristics.IDENTITY_FINISH));
  81. return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED, Characteristics.CONCURRENT));
  82. }
  83.  
  84. public static void main(String[] args) {
  85. System.out.println(Runtime.getRuntime().availableProcessors());
  86.  
  87. List<String> list = Arrays.asList("hello", "world", "welcome", "hello", "a", "b", "c", "d", "e", "f", "g");
  88. Set<String> set = new HashSet<>();
  89. set.addAll(list);
  90.  
  91. System.out.println("set: " + set);
  92.  
  93. System.out.println("----------");
  94.  
  95. //串行执行时combiner并不会得到调用,combiner只在并行流时会得到调用
  96. // Map<String, String> map = set.stream().parallel().sequential().parallel().collect(new MySetCollector2<>());
  97. Map<String, String> map = set.parallelStream().collect(new MySetCollector2<>());
  98. System.out.println(map);
  99. }
  100. }
  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3. import java.util.IntSummaryStatistics;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Optional;
  7.  
  8. import static java.util.stream.Collectors.averagingInt;
  9. import static java.util.stream.Collectors.collectingAndThen;
  10. import static java.util.stream.Collectors.counting;
  11. import static java.util.stream.Collectors.groupingBy;
  12. import static java.util.stream.Collectors.joining;
  13. import static java.util.stream.Collectors.maxBy;
  14. import static java.util.stream.Collectors.minBy;
  15. import static java.util.stream.Collectors.partitioningBy;
  16. import static java.util.stream.Collectors.summarizingInt;
  17. import static java.util.stream.Collectors.summingInt;
  18. import static java.util.stream.Collectors.toList;
  19.  
  20. public class StreamTest1 {
  21.  
  22. public static void main(String[] args) {
  23. Student student1 = new Student("zhangsan", 80);
  24. Student student2 = new Student("lisi", 90);
  25. Student student3 = new Student("wangwu", 100);
  26. Student student4 = new Student("zhaoliu", 90);
  27. Student student5 = new Student("zhaoliu", 90);
  28.  
  29. List<Student> students = Arrays.asList(student1, student2, student3, student4, student5);
  30.  
  31. // List<Student> students1 = students.stream().collect(toList());
  32. // students1.forEach(System.out::println);
  33. // System.out.println("------------");
  34. //
  35. //
  36. // System.out.println("count: " + students.stream().collect(counting()));
  37. // System.out.println("count: " + students.stream().count());
  38. // System.out.println("------------");
  39. //
  40. //
  41. // students.stream().collect(minBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
  42. //
  43. // students.stream().collect(maxBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
  44. //
  45. // System.out.println(students.stream().collect(averagingInt(Student::getScore)));
  46. //
  47. // System.out.println(students.stream().collect(summingInt(Student::getScore)));
  48. //
  49. // IntSummaryStatistics intSummaryStatistics = students.stream().collect(summarizingInt(Student::getScore));
  50. // System.out.println(intSummaryStatistics);
  51. // System.out.println("------------");
  52. //
  53. // System.out.println(students.stream().map(Student::getName).collect(joining()));
  54. // System.out.println(students.stream().map(Student::getName).collect(joining(", ")));
  55. // System.out.println(students.stream().map(Student::getName).collect(joining(", ", "<begin> ", " <end>")));
  56. // System.out.println("------------");
  57. //
  58.  
  59. // Map<Integer, Map<String, List<Student>>> map = students.stream().
  60. // collect(groupingBy(Student::getScore, groupingBy(Student::getName)));
  61. // System.out.println(map);
  62. // System.out.println("------------");
  63.  
  64. //
  65. // Map<Boolean, List<Student>> map2 = students.stream().
  66. // collect(partitioningBy(student -> student.getScore() > 80));
  67. // System.out.println(map2);
  68. // System.out.println("------------");
  69. //
  70.  
  71. // Map<Boolean, Map<Boolean, List<Student>>> map3 = students.stream().
  72. // collect(partitioningBy(student -> student.getScore() > 80,
  73. // partitioningBy(student -> student.getScore() > 90)));
  74. // System.out.println(map3);
  75. // System.out.println("------------");
  76.  
  77. //
  78. // Map<Boolean, Long> map4 = students.stream().
  79. // collect(partitioningBy(student -> student.getScore() > 80, counting()));
  80. // System.out.println(map4);
  81. // System.out.println("------------");
  82. ////
  83. // Map<String, Student> map5 = students.stream().
  84. // collect(groupingBy(Student::getName,
  85. // collectingAndThen(minBy(Comparator.comparingInt(Student::getScore)),
  86. // Optional::get)));
  87. // System.out.println(map5);
  88. }
  89. }
  1. import java.util.Arrays;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;
  5.  
  6. public class StreamTest2 {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. List<String> list = Arrays.asList("nihao", "hello", "world", "welcome");
  11.  
  12. // Collections.sort(list, (item1, item2) -> item1.length() - item2.length());
  13. // Collections.sort(list, (item1, item2) -> item2.length() - item1.length());
  14.  
  15. // Collections.sort(list, Comparator.comparingInt(String::length).reversed());
  16. //// 此处lambda参数的类型推断无法推断出item为String类型,需要显式指定;原因在于这是一个独立的参数,并不是通过list调用方法来得出的
  17. // Collections.sort(list, Comparator.comparingInt((String item) -> item.length()).reversed());
  18. //// 如下代码无法编译通过,因为lambda参数要求参数类型应该是String或是String的父类,而Boolean则不是
  19. // Collections.sort(list, Comparator.comparingInt((Boolean item) -> 1).reversed());
  20.  
  21. //// Collections的sort就是调用List的sort实现的
  22. // list.sort(Comparator.comparingInt(String::length).reversed());
  23. //// 如下代码必须要显式声明item的类型为String
  24. // list.sort(Comparator.comparingInt((String item) -> item.length()).reversed());
  25. //
  26. //
  27. // Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER));
  28. //
  29. // // 为何下面这个thenComparing中的参数类型可以推断出来?
  30. // Collections.sort(list, Comparator.comparingInt(String::length).
  31. // thenComparing((item1, item2) -> item1.toLowerCase().compareTo(item2.toLowerCase())));
  32. // Collections.sort(list, Comparator.comparingInt(String::length).
  33. // thenComparing(Comparator.comparing(String::toLowerCase)));
  34. // Collections.sort(list, Comparator.comparingInt(String::length).
  35. // thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())));
  36. ////
  37. // // welcome, world, nihao, hello
  38. // Collections.sort(list, Comparator.comparingInt(String::length).reversed().
  39. // thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())));
  40. //
  41. // // welcome, world, nihao, hello, 注意:thenComparing都是根据前一个compare的结果来决定此次是否进行再次排序,
  42. // // 如果前一次排序不返回0,那么此次排序结果就直接返回之前的排序结果
  43.  
  44. Collections.sort(list, Comparator.comparingInt(String::length).reversed().
  45. thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())).
  46. thenComparing(Comparator.reverseOrder()));
  47.  
  48. System.out.println(list);
  49. }
  50. }
  1. public class Student {
  2.  
  3. private String name;
  4.  
  5. private int score;
  6.  
  7. public Student(String name, int score) {
  8. this.name = name;
  9. this.score = score;
  10. }
  11.  
  12. public String getName() {
  13. return name;
  14. }
  15.  
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19.  
  20. public int getScore() {
  21. return score;
  22. }
  23.  
  24. public void setScore(int score) {
  25. this.score = score;
  26. }
  27.  
  28. @Override
  29. public String toString() {
  30. return "Student{" +
  31. "name='" + name + '\'' +
  32. ", score=" + score +
  33. '}';
  34. }
  35. }

stream2的更多相关文章

  1. java8 Stream2

    new Thread(() -> System.out.println("lambda表达式,取代匿名函数......")).start(); Stream.of(" ...

  2. 深入node之Transform

    Transform流特性 在开发中直接接触Transform流的情况不是很多,往往是使用相对成熟的模块或者封装的API来完成流的处理,最为特殊的莫过于through2模块和gulp流操作.那么,Tra ...

  3. 最好的.NET开源免费ZIP库DotNetZip(.NET组件介绍之三)

    在项目开发中,除了对数据的展示更多的就是对文件的相关操作,例如文件的创建和删除,以及文件的压缩和解压.文件压缩的好处有很多,主要就是在文件传输的方面,文件压缩的好处就不需要赘述,因为无论是开发者,还是 ...

  4. 一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)

    在目前的软件项目中,都会较多的使用到对文档的操作,用于记录和统计相关业务信息.由于系统自身提供了对文档的相关操作,所以在一定程度上极大的简化了软件使用者的工作量. 在.NET项目中如果用户提出了相关文 ...

  5. 如何运行Spark程序

    [hxsyl@CentOSMaster spark-2.0.2-bin-hadoop2.6]# ./bin/spark-submit --class org.apache.spark.examples ...

  6. 小菜学习设计模式(四)—原型(Prototype)模式

    前言 设计模式目录: 小菜学习设计模式(一)—模板方法(Template)模式 小菜学习设计模式(二)—单例(Singleton)模式 小菜学习设计模式(三)—工厂方法(Factory Method) ...

  7. C# DESC加密

    DESC加密方法 直接上代码: 1.加密 /// <summary> /// 加密 /// </summary> /// <param name="obj&qu ...

  8. [MVC_Json序列化]Json字符串反序列化成C#对象

    上一篇中有Json序列化相关问题得到了解决. 那么结果集为Json串时,如何将Json串转成C#对象呢? 现举例说明: -现有如下字符串数据 string k = "{\"ring ...

  9. Matlab绘图函数一览

    要查看Matlab所有绘图函数,请从Matlab主界面菜单查看“绘图目录”,或从Matlab帮助文档查看“Types of MATLAB Plots”(在线版本).本文的图和英文解释摘自Matlab帮 ...

随机推荐

  1. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-009Polymorphic collections(@OneToMany(mappedBy = "user")、@ManyToOne、)

    一.代码 1. package org.jpwh.model.inheritance.associations.onetomany; import org.jpwh.model.Constants; ...

  2. Luogu 3530 [POI2012]FES-Festival

    我是真的不会写差分约束啊呜呜呜…… BZOJ 2788被权限了. 首先对于第一个限制$x + 1 = y$,可以转化成$x + 1 \leq y \leq x + 1$, 所以连一条$(y, x, - ...

  3. Luogu 2254 [NOI2005]瑰丽华尔兹

    简单dp,设$f_{i,j,k}$表示第i个时间段,钢琴处在(j,k)位置移动距离的最大值,那么有转移 $f_{i, j, k} = max(f_{i - 1, j, k}) ,  f_{i, j, ...

  4. appium自动化安装(二)

    第二节  安装Android开发环境 如果你的环境是MAC那么可以直接跳过这一节.就像我们在用Selenium进行web自动化测试的时候一样,我们需要一个浏览器来执行测试脚本.那么移动端自动化测试,我 ...

  5. python--输出spwm的数组

    python的功能是非常强大的,这个例子使用python编写的输出spwm数组(不对,在C语言或者其他语言叫做数组,在这里叫做list.)的程序,我们在单片机程序里调用这个程序,可以达到输出spwm波 ...

  6. arcgis调用国家天地图wfs服务

    1.国家天地图wfs地址 getcapabilities http://www.tianditu.com/wfssearch.shtml?request=getcapabilities&ser ...

  7. C#代码标识符命名规范

    总体原则:命名一定要体现其在程序中的作用: Camel命名法:第一个单词的首字母小写,其余每个单词的首字母大写:多用给变量或者字段命名:给字段命名必须以下划线开始: Pascal命名法:每个单词的首字 ...

  8. Kinect插件使用

    Kinect Scripts文件夹下所有managers(管理器)的用途: 这些在KinectScripts文件夹下的管理器都是组件,你可以根据你想实现的功能在项目中使用它. KinectManage ...

  9. 算法训练 Cowboys(DP)

    问题描述 一个间不容发的时刻:n个牛仔站立于一个环中,并且每个牛仔都用左轮手枪指着他旁边的人!每个牛仔指着他顺时针或者逆时针方向上的相邻的人.正如很多西部片那样,在这一刻,绳命是入刺的不可惜……对峙的 ...

  10. 好程序员web前端分享CSS元素类型

    好程序员web前端分享CSS元素类型 目标 1.元素类型分类依据和元素类型分类 2.元素类型的转换 3.inline-block元素类型的应用 4.置换和非置换元素的概念和应用案例 一.元素类型分类依 ...