分类:简单计算, 收集到映射表中 , 群组和分组, 下游收集器, 约简操作 reduce()

  1. ArrayList<String> arrayList = new ArrayList<>();
  2. arrayList.add("aa");
  3. arrayList.add("aA");
  4. arrayList.add("bbb");
  5. arrayList.add("a1c2");
  6. arrayList.add("a1a");
  7. arrayList.add("c");
  8. Supplier<Stream<String>> supplier = ()->arrayList.stream();

直接输出结果

  1. /***
  2. * 直接输出结果
  3. */
  4. //1. iterator()相关 ->旧式迭代器
  5. //(1)iterator
  6. System.out.println("----直接输出结果--旧式迭代器-----start--");
  7. Iterator<String> iterator = arrayList.stream().parallel().iterator();
  8. while(iterator.hasNext()){
  9. System.out.println(iterator.next());
  10. }
  11. System.out.println();
  12. //forEachRemaining()
  13. arrayList.iterator().forEachRemaining((x)->System.out.println(x.toString()));
  14. System.out.println("----直接输出结果--旧式迭代器-----end--");
  15. System.out.println();
  16. //(2) spliterator()
  17. Spliterator<String> spliterator = arrayList.stream().spliterator();
  18. while(spliterator.tryAdvance((n)->System.out.println(n))){}
  19. System.out.println();
  20. spliterator = arrayList.stream().spliterator();
  21. spliterator.forEachRemaining((n)->System.out.println(n));
  22. System.out.println();
  23. Spliterator<String> spliterator2 = arrayList.stream().spliterator().trySplit();
  24. spliterator2.forEachRemaining((n)->System.out.println(n));
  25. spliterator2.forEachRemaining((n)->System.out.println(n));
  26. System.out.println();
  27. //2. forEach() ->parallel()返回的结果顺序不确定
  28. System.out.println("----直接输出结果--.stream().parallel().forEach()-----start--");
  29. arrayList.stream().parallel().forEach(n->System.out.println(n));
  30. System.out.println("----直接输出结果--.stream().parallel().forEach()-----end--");
  31. System.out.println();
  32. //3. forEachOrdered() ->parallel()返回的结果顺序与流中的顺序相同
  33. System.out.println("----直接输出结果--.stream().parallel().forEachOrdered()-----start--");
  34. arrayList.stream().parallel().forEachOrdered(n->System.out.println(n));
  35. System.out.println("----直接输出结果--.stream().parallel().forEachOrdered()-----end--");
  36. System.out.println();
  37. System.out.println();
  38. System.out.println();
  39. System.out.println();
  40. System.out.println();

简单的计算

  1. //1. count() 数量
  2. System.out.println(supplier.get().count());
  3. System.out.println();
  4. //2. max() 最大数值
  5. System.out.println(supplier.get().max(String::compareToIgnoreCase).orElse(""));
  6. System.out.println();
  7. //3. min() 最小数值
  8. System.out.println(supplier.get().min(String::compareToIgnoreCase).orElse(""));
  9. System.out.println();
  10. //4. findFirst(), 非空集合中第一个
  11. //一般结合filer()==>findFirst==>找到匹配条件中第一个
  12. String findFirstValue = supplier.get().findFirst().orElse("");
  13. System.out.println(findFirstValue);
  14. findFirstValue = supplier.get().filter(x->x.length()>2).findFirst().orElse("");
  15. System.out.println(findFirstValue);
  16. findFirstValue = supplier.get().filter(x->x.length()>2).sorted().findFirst().orElse("");
  17. System.out.println(findFirstValue);
  18. findFirstValue = supplier.get().filter(x->x.length()>2).sorted(Comparator.comparing(String::length).thenComparing(String::compareTo).reversed()).findFirst().orElse("");
  19. System.out.println(findFirstValue);
  20. System.out.println();
  21. //5. findAny(), 非空集合中任意一个
  22. //一般结合filer()==>findAny==>找到匹配任意匹配,表示能够匹配
  23. String findAnyValue = supplier.get().filter(x->x.length()>4).findAny().orElse("");
  24. System.out.println(!findAnyValue.equals(""));
  25. System.out.println();
  26. //6. anyMatch(), 任意元素有无匹配
  27. //直接使用看是否有匹配
  28. boolean anyMatch = supplier.get().anyMatch(x->x.length()>3);
  29. System.out.println(anyMatch);
  30. System.out.println();
  31. //7. allMatch(), 所有元素有无匹配
  32. //直接使用看是否有匹配
  33. boolean allMatch = supplier.get().allMatch(x->x.length()>0);
  34. System.out.println(allMatch);
  35. System.out.println();
  36. //8. noneMatch(), 没有任意元素有无匹配
  37. //直接使用看是否有匹配
  38. boolean noneMatch = supplier.get().noneMatch(x->x.length()>4);
  39. System.out.println(noneMatch);
  40. System.out.println();

收集到映射表中

  1. /***
  2. * 收集到映射表中
  3. */
  4. //1.toArray()
  5. System.out.println("----收集到数据结构中--.stream().toArray()-----start--");
  6. String[] stringArray = arrayList.stream().toArray(String[]::new);
  7. System.out.println(Arrays.toString(stringArray));
  8. System.out.println();
  9. System.out.println(Arrays.toString(arrayList.stream().toArray()));
  10. System.out.println("----收集到数据结构中--.stream().toArray()-----end--");
  11. System.out.println();
  12. //2.collect() 收集元素到集合, 总和/平均值/最大/最小值
  13. ArrayList<NamePhoneEmail> myList = new ArrayList<>();
  14. myList.add(new NamePhoneEmail("Larry", "555-5555", "Larry@HerbSchildt.com"));
  15. myList.add(new NamePhoneEmail("James", "555-4444", "James@HerbSchildt.com"));
  16. myList.add(new NamePhoneEmail("Mary", "555-3333", "Mary@HerbSchildt.com"));
  17. //(1) toList() 使用Collectors.toList()
  18. System.out.println("----收集到数据结构中--.stream().map().collect(.toList()).forEach()-----start-------");
  19. myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(Collectors.toList()).forEach(n->System.out.println(n.name+" "+n.phonenum));
  20. System.out.println();
  21. //在循环之前先做map()处理
  22. myList.stream().map((a) -> a.toString()).collect(Collectors.toList()).forEach(System.out::println);
  23. System.out.println("----收集到数据结构中--.stream().map().collect(.toList()).forEach()-----end-------");
  24. System.out.println();
  25. System.out.println();
  26. //(2) toSet() 使用Collectors.toSet()
  27. System.out.println("----收集到数据结构中--.stream().map().collect(.toSet()).forEach()-----start-------");
  28. myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(Collectors.toSet()).forEach(n->System.out.println(n.name+" "+n.phonenum));
  29. System.out.println("----收集到数据结构中--.stream().map().collect(.toSet()).forEach()-----end-------");
  30. System.out.println();
  31. System.out.println();
  32. //(3) ->TreeSet 使用Collectors.toCollection() TreeSet自动排序
  33. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(TreeSet::new)).forEach()-----start-------");
  34. TreeSet<String> toTreeSet = arrayList.stream().collect(Collectors.toCollection(TreeSet::new));
  35. toTreeSet.forEach(n->System.out.println(n));
  36. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(TreeSet::new)).forEach()-----end-------");
  37. System.out.println();
  38. System.out.println();
  39. //(4) ->ArrayList 使用Collectors.toCollection()
  40. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(ArrayList::new)).forEach()-----start-------");
  41. ArrayList<String> toArrayList = arrayList.stream().collect(Collectors.toCollection(ArrayList::new));
  42. toArrayList.forEach(n->System.out.println(n));
  43. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(ArrayList::new)).forEach()-----end-------");
  44. System.out.println();
  45. System.out.println();
  46. System.out.println();
  47. System.out.println();
  48. //(5) ->toMap 收集到映射表中
  49. //1) 指定keyMapper和valueMapper
  50. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper)).forEach()-----start-------");
  51. Map<String, String> toMap = myList.stream().collect(
  52. Collectors.toMap(
  53. NamePhoneEmail::getName, //keyMapper
  54. NamePhoneEmail::getPhonenum //valueMapper
  55. ));
  56. toMap.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
  57. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper)).forEach()-----end-------");
  58. System.out.println();
  59. System.out.println();
  60. //2) 指定keyMapper, valueMapper, mergeFunction
  61. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction)).forEach()-----start-------");
  62. Stream<Locale> localesStream = Stream.of(Locale.getAvailableLocales());
  63. //通过指定的mergeFunction, 解决冲突
  64. Map<String, String> languageNames = localesStream.collect(
  65. Collectors.toMap(
  66. Locale::getDisplayLanguage, //keyMapper
  67. l->l.getDisplayLanguage(l), //valueMapper
  68. (existingValue, newValue)->existingValue //mergeFunction, 合并两个 keyMapper 相同的值
  69. ));
  70. languageNames.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
  71. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction)).forEach()-----end-------");
  72. System.out.println();
  73. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper(Set), mergeFunction)).forEach()-----start-------");
  74. localesStream = Stream.of(Locale.getAvailableLocales());
  75. Map<String, Set<String>> countryLanguageSets = localesStream.collect(
  76. Collectors.toMap(
  77. Locale::getDisplayCountry, //keyMapper
  78. l -> Collections.singleton(l.getDisplayLanguage()), //valueMapper Returns an immutable set containing only the specified object
  79. (a, b) -> { // union of a and b //mergeFunction
  80. Set<String> union = new HashSet<>(a);
  81. union.addAll(b);
  82. return union;
  83. }
  84. ));
  85. countryLanguageSets.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
  86. System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper(Set), mergeFunction)).forEach()-----end-------");
  87. System.out.println();
  88. System.out.println();
  89. //(6) to LinkedList
  90. System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to LinkedList---start-------");
  91. LinkedList<NamePhone> nkList = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(
  92. ()->new LinkedList<>(),
  93. (list, element) -> list.add(element),
  94. (listA, listB)->listA.addAll(listB)
  95. );
  96. nkList.forEach(n->System.out.println(n.name+" "+n.phonenum));
  97. System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to LinkedList---end-------");
  98. System.out.println();
  99. System.out.println();
  100. //(7) to HashSet
  101. System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to HashSet---start-------");
  102. HashSet<NamePhone> hsSet = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(
  103. HashSet::new,
  104. HashSet::add,
  105. HashSet::addAll
  106. );
  107. hsSet.forEach(n->System.out.println(n.name+" "+n.phonenum));
  108. System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to HashSet---end-------");
  109. System.out.println();
  110. System.out.println();
  111. //(8)总和, 平均值, 最大值, 最小值
  112. ArrayList<Integer> integerList = new ArrayList<>();
  113. integerList.add(23);
  114. integerList.add(66);
  115. integerList.add(888);
  116. integerList.add(999);
  117. integerList.add(1024);
  118. //总和
  119. Integer integerCollect = integerList.stream().collect(Collectors.summingInt(Integer::intValue));
  120. System.out.println(integerCollect);
  121. //总和, 数目, 平均值, 最大值, 最小值
  122. IntSummaryStatistics intSummaryStatistics = integerList.stream().collect(Collectors.summarizingInt(Integer::intValue));
  123. System.out.println(intSummaryStatistics.getSum());
  124. System.out.println(intSummaryStatistics.getCount());
  125. System.out.println(intSummaryStatistics.getAverage());
  126. System.out.println(intSummaryStatistics.getMax());
  127. System.out.println(intSummaryStatistics.getMin());
  128. System.out.println("------intSummaryStatistics-------");
  129. ArrayList<Long> longList = new ArrayList<>();
  130. longList.add(23l);
  131. longList.add(66l);
  132. longList.add(888l);
  133. longList.add(999l);
  134. longList.add(1024l);
  135. Long longCollect = longList.stream().collect(Collectors.summingLong(Long::longValue));
  136. System.out.println(longCollect);
  137. LongSummaryStatistics longSummaryStatistics = longList.stream().collect(Collectors.summarizingLong(Long::longValue));
  138. System.out.println(longSummaryStatistics.getSum());
  139. System.out.println(longSummaryStatistics.getCount());
  140. System.out.println(longSummaryStatistics.getAverage());
  141. System.out.println(longSummaryStatistics.getMax());
  142. System.out.println(longSummaryStatistics.getMin());
  143. System.out.println("------longSummaryStatistics-------");
  144. ArrayList<Double> doubleList = new ArrayList<>();
  145. doubleList.add(23.2);
  146. doubleList.add(66.3);
  147. doubleList.add(888.5);
  148. doubleList.add(999.6);
  149. doubleList.add(1024.8);
  150. Double doubleCollect = doubleList.stream().collect(Collectors.summingDouble(Double::doubleValue));
  151. System.out.println(doubleCollect);
  152. DoubleSummaryStatistics doubleSummaryStatistics = doubleList.stream().collect(Collectors.summarizingDouble(Double::doubleValue));
  153. System.out.println(doubleSummaryStatistics.getSum());
  154. System.out.println(doubleSummaryStatistics.getCount());
  155. System.out.println(doubleSummaryStatistics.getAverage());
  156. System.out.println(doubleSummaryStatistics.getMax());
  157. System.out.println(doubleSummaryStatistics.getMin());
  158. System.out.println("------doubleSummaryStatistics-------");
  159. //(9) joining() 指定连接符
  160. System.out.println("----收集到数据结构中--.stream().collect(Collectors.joining())-----start-------");
  161. String collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining());
  162. System.out.println(collectJoining);
  163. //指定连接符
  164. collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining(";"));
  165. System.out.println(collectJoining);
  166. //指定连接符, 前缀, 后缀
  167. collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining(";","prefix "," suffix"));
  168. System.out.println(collectJoining);
  169. System.out.println("----收集到数据结构中--.stream().collect(Collectors.joining())-----end-------");
  170. System.out.println();
  171. System.out.println();

群组和分组
  1. /***
  2. * 群组和分组
  3. */
  4. //1. groupingBy()
  5. //1)直接使用 groupingBy() 按指定元素分组
  6. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element)).forEach()-----start-------");
  7. localesStream = Stream.of(Locale.getAvailableLocales());
  8. Map<String, List<Locale>> countryToLocalsMap = localesStream.collect(Collectors.groupingBy(Locale::getCountry));
  9. countryToLocalsMap.entrySet().forEach((n)->{
  10. System.out.print(n.getKey()+":");
  11. n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
  12. System.out.println();
  13. });
  14. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element)).forEach()-----end-------");
  15. System.out.println();
  16. System.out.println();
  17. //2) groupingBy后toList, 和直接使用.groupingBy(element) 结果相同
  18. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toList)).forEach()-----start-------");
  19. localesStream = Stream.of(Locale.getAvailableLocales());
  20. Map<String, List<Locale>> groupingByToList = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.toList()));
  21. groupingByToList.entrySet().forEach((n)->{
  22. System.out.print(n.getKey()+":");
  23. n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
  24. System.out.println();
  25. });
  26. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toList)).forEach()-----end-------");
  27. System.out.println();
  28. System.out.println();
  29. //3) groupingBy后toSet
  30. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toSet)).forEach()-----start-------");
  31. localesStream = Stream.of(Locale.getAvailableLocales());
  32. Map<String, Set<Locale>> groupingByToSet = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.toSet()));
  33. groupingByToSet.entrySet().forEach((n)->{
  34. System.out.print(n.getKey()+":");
  35. n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
  36. System.out.println();
  37. });
  38. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toSet)).forEach()-----end-------");
  39. System.out.println();
  40. System.out.println();
  41. System.out.println();
  42. //4) groupingByConcurrent() 得到一个并行映射表
  43. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingByConcurrent(element)).forEach()-----start-------");
  44. localesStream = Stream.of(Locale.getAvailableLocales());
  45. countryToLocalsMap = localesStream.collect(Collectors.groupingByConcurrent(Locale::getCountry));
  46. countryToLocalsMap.entrySet().forEach((n)->{
  47. System.out.print(n.getKey()+":");
  48. n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
  49. System.out.println();
  50. });
  51. System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingByConcurrent(element)).forEach()-----end-------");
  52. System.out.println();
  53. System.out.println();
  54. System.out.println();
  55. //a) groupingByConcurrent后toList, 和直接使用.groupingByConcurrent(element) 结果相同
  56. //b) groupingByConcurrent后toSet
  57. //5)使用partitioningBy() 按照指定条件(true or false)分组
  58. System.out.println("----收集到数据结构中--.stream().collect(Collectors.partitioningBy(Predicate<? super T> predicate)).forEach()-----start-------");
  59. localesStream = Stream.of(Locale.getAvailableLocales());
  60. Map<Boolean, List<Locale>> booleanLocalesStream = localesStream.collect(Collectors.partitioningBy((Locale l)->l.getCountry().equals("CN")));
  61. List<Locale> trueList = booleanLocalesStream.get(true);
  62. System.out.println("trueList "+trueList);
  63. List<Locale> falseList = booleanLocalesStream.get(false);
  64. System.out.println("falseList "+falseList);
  65. System.out.println("----收集到数据结构中--.stream().collect(Collectors.partitioningBy(Predicate<? super T> predicate)).forEach()-----end-------");
  66. System.out.println();
  67. System.out.println();
  68. System.out.println();
  69. //a) partitioningBy后toList, 和直接使用.partitioningBy(element) 结果相同
  70. //b) partitioningBy后toSet
下游收集器
  1. /***
  2. * 下游收集器
  3. */
  4. ArrayList<City> cityArrayList = new ArrayList<>();
  5. cityArrayList.add(new City("AAA", "0001", 1234, 1234, 1234.1));
  6. cityArrayList.add(new City("ABA", "0001", 4321, 4321, 4321.2));
  7. cityArrayList.add(new City("BAA", "0002", 1004, 1004, 1004.6));
  8. cityArrayList.add(new City("BBA", "0002", 1034, 1034, 1034.8));
  9. //1. counting()
  10. //在groupingBy(), groupingByConcurrent(), partitioningBy()之后, 处理下游(接下来)的值
  11. //1) Collectors.counting() 计算收集到的元素个数
  12. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), counting()).forEach()-----start-------");
  13. localesStream = Stream.of(Locale.getAvailableLocales());
  14. Map<String, Long> countryToLocalsCountMap = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.counting()));
  15. countryToLocalsCountMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue()));
  16. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), counting()).forEach()-----end-------");
  17. System.out.println();
  18. System.out.println();
  19. System.out.println("----收集到数据结构中--.stream().collect(groupingByConcurrent(), counting()).forEach()-----start-------");
  20. localesStream = Stream.of(Locale.getAvailableLocales());
  21. ConcurrentMap<String, Long> countryToLocalsConcurrentCountMap = localesStream.collect(Collectors.groupingByConcurrent(Locale::getCountry, Collectors.counting()));
  22. countryToLocalsConcurrentCountMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue()));
  23. System.out.println("----收集到数据结构中--.stream().collect(groupingByConcurrent(), counting()).forEach()-----end-------");
  24. System.out.println();
  25. System.out.println();
  26. System.out.println("----收集到数据结构中--.stream().collect(partitioningBy(), counting()).forEach()-----start-------");
  27. localesStream = Stream.of(Locale.getAvailableLocales());
  28. Map<Boolean, Long> booleanLocalesMap = localesStream.collect(Collectors.partitioningBy((Locale l)->l.getCountry().equals("CN"), Collectors.counting()));
  29. System.out.println("trueList count:"+booleanLocalesMap.get(true));
  30. System.out.println("falseList count:"+booleanLocalesMap.get(false));
  31. booleanLocalesMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue()));
  32. System.out.println("----收集到数据结构中--.stream().collect(partitioningBy(), counting()).forEach()-----end-------");
  33. System.out.println();
  34. System.out.println();
  35. //2. Collectors.summing() 计算收集到的元素的和
  36. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingInt()).forEach()-----start-------");
  37. Map<String, Integer> collectCitySummingIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingInt(City::getIntPopulation)));
  38. collectCitySummingIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingInt:"+n.getValue()));
  39. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingInt()).forEach()-----end-------");
  40. System.out.println();
  41. System.out.println();
  42. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingLong()).forEach()-----start-------");
  43. Map<String, Long> collectCitySummingLongMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingLong(City::getLongPopulation)));
  44. collectCitySummingLongMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingLong:"+n.getValue()));
  45. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingLong()).forEach()-----end-------");
  46. System.out.println();
  47. System.out.println();
  48. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingDouble()).forEach()-----start-------");
  49. Map<String, Double> collectCitySummingDoubleMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingDouble(City::getDoublePopulation)));
  50. collectCitySummingDoubleMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingDouble:"+n.getValue()));
  51. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingDouble()).forEach()-----end-------");
  52. System.out.println();
  53. System.out.println();
  54. //3. Collectors.maxBy() 计算收集到的元素的最大值 传入比较器
  55. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), maxBy()).forEach()-----start-------");
  56. Map<String, Optional<City>> collectCityMaxIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.maxBy(Comparator.comparing(City::getIntPopulation))));
  57. collectCityMaxIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , getIntPopulation maxBy:"+n.getValue().get().getIntPopulation()));
  58. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), maxBy()).forEach()-----end-------");
  59. System.out.println();
  60. System.out.println();
  61. //4. Collectors.minBy() 计算收集到的元素的最小值
  62. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), minBy()).forEach()-----start-------");
  63. Map<String, Optional<City>> collectCityMinIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.minBy(Comparator.comparing(City::getIntPopulation))));
  64. collectCityMinIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , getIntPopulation minBy:"+n.getValue().get().getIntPopulation()));
  65. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), minBy()).forEach()-----end-------");
  66. System.out.println();
  67. System.out.println();
  68. //5. Collectors.mapping() ** 两层操作,第一遍groupby(), 第二遍再mapping()
  69. //两层操作,第一层,按照getState分组后;第二层,拿getName得最大
  70. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), mapping()).forEach()-----start-------");
  71. Map<String, Optional<String>> collectCityMaxStatusMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.mapping(City::getName, Collectors.maxBy(String::compareTo))));
  72. collectCityMaxStatusMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , collectCityMaxStatusMap maxBy:"+n.getValue().get()));
  73. System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), mapping()).forEach()-----end-------");
  74. System.out.println();
  75. System.out.println();
  76. //可以调用min()
约简操作 reduce()

  1. /***
  2. * 约简操作 reduce() 从流中计算值
  3. *
  4. * V1 op V2 op V3 ... op VN
  5. *
  6. * 约简操作中, 流中元素的顺序不能有限制,
  7. * 可以应用于约简操作的: 求和, 乘积, 字符串连接,求最大值, 求最小值, 求集合的并和交
  8. * 不可应用于约简操作的: 减法, 除法
  9. */
  10. List<Integer> integerValues = Arrays.asList(11,22,33,44,55,66);
  11. //1. 简单的示例
  12. //求和, 最大值, 最小值
  13. Optional<Integer> sumOptional = integerValues.stream().reduce(Integer::sum);//(x,y) -> (x+y)
  14. if(sumOptional.isPresent()){
  15. System.out.println(sumOptional.get());
  16. }
  17. Optional<Integer> maxOptional = integerValues.stream().reduce(Integer::max);
  18. if(maxOptional.isPresent()){
  19. System.out.println(maxOptional.get());
  20. }
  21. Optional<Integer> minOptional = integerValues.stream().reduce(Integer::min);
  22. if(minOptional.isPresent()){
  23. System.out.println(minOptional.get());
  24. }
  25. Optional<Integer> multiplyOptional = integerValues.stream().reduce((x,y)->(x*y));
  26. if(multiplyOptional.isPresent()){
  27. System.out.println(multiplyOptional.get());
  28. }
  29. //2. 传入初始值(幺元值), 作为计算的起点 stream()
  30. //T reduce(T identity, BinaryOperator<T> accumulator)
  31. //identity只在第一次使用
  32. /**
  33. a:1 b:11
  34. a:11 b:22
  35. a:242 b:33
  36. a:7986 b:44
  37. a:351384 b:55
  38. a:19326120 b:66
  39. 1275523920
  40. */
  41. Integer reduce = integerValues.stream().reduce(1, (a,b)->{
  42. System.out.println("a:"+a+" b:"+b);
  43. return a+b;
  44. });
  45. System.out.println(reduce);
  46. //3. 传入初始值(幺元值), 作为计算的起点; parallelStream()
  47. //<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
  48. //identity每次都会使用, 和accumulator结合使用时
  49. //combiner用来处理accumulator的结果
  50. //使用stream()时combiner不起作用; 只有parallelStream() 并行流 时combiner才起作用
  51. Integer reduce2 = integerValues.parallelStream().reduce(
  52. 1,
  53. (a,b)->{
  54. System.out.println("a+b a:"+a+" b:"+b);
  55. return a+b;
  56. },
  57. (a,b)->{
  58. System.out.println("a*b a:"+a+" b:"+b);
  59. return a*b;
  60. }
  61. );
  62. System.out.println(reduce2);

辅助类

  1. class City{
  2. private String name;
  3. private String state;
  4. private int intPopulation;
  5. private long longPopulation;
  6. private double doublePopulation;
  7. public City(String name, String state, int intPopulation, long longPopulation, double doublePopulation) {
  8. this.name = name;
  9. this.state = state;
  10. this.intPopulation = intPopulation;
  11. this.longPopulation = longPopulation;
  12. this.doublePopulation = doublePopulation;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public String getState() {
  21. return state;
  22. }
  23. public void setState(String state) {
  24. this.state = state;
  25. }
  26. public int getIntPopulation() {
  27. return intPopulation;
  28. }
  29. public void setIntPopulation(int intPopulation) {
  30. this.intPopulation = intPopulation;
  31. }
  32. public long getLongPopulation() {
  33. return longPopulation;
  34. }
  35. public void setLongPopulation(long longPopulation) {
  36. this.longPopulation = longPopulation;
  37. }
  38. public double getDoublePopulation() {
  39. return doublePopulation;
  40. }
  41. public void setDoublePopulation(double doublePopulation) {
  42. this.doublePopulation = doublePopulation;
  43. }
  44. }
  45. class NamePhoneEmail {
  46. String name;
  47. String phonenum;
  48. String email;
  49. NamePhoneEmail(String n, String p, String e) {
  50. name = n;
  51. phonenum = p;
  52. email = e;
  53. }
  54. public String getName() {
  55. return name;
  56. }
  57. public void setName(String name) {
  58. this.name = name;
  59. }
  60. public String getPhonenum() {
  61. return phonenum;
  62. }
  63. public void setPhonenum(String phonenum) {
  64. this.phonenum = phonenum;
  65. }
  66. public String getEmail() {
  67. return email;
  68. }
  69. public void setEmail(String email) {
  70. this.email = email;
  71. }
  72. @Override
  73. public String toString() {
  74. return "name:"+name+",phonenum:"+phonenum+",email:"+email;
  75. }
  76. }
  77. class NamePhone {
  78. String name;
  79. String phonenum;
  80. NamePhone(String n, String p) {
  81. name = n;
  82. phonenum = p;
  83. }
  84. }











J2SE 8的流库 --- 收集处理结果的更多相关文章

  1. J2SE 8的流库 --- 生成流

    本文介绍了如何产生J2SE 8的流, 包括基本类型的流IntStream, LongStream, DoubleStream . 展现流的方法 public static <T> void ...

  2. J2SE 8的流库 --- 转换流, 得到的还是流

    流的转换, 按照条件过滤/映射/摊平/截取/丢弃/连接/去重/排序. 辅助方法 public static int myCompare(String x, String y) { if(x.lengt ...

  3. J2SE 8的流库 --- 基本类型流的使用

    展现流的方法 public static <T> void show(String title, Stream<T> stream){ System.out.println(& ...

  4. [一] java8 函数式编程入门 什么是函数式编程 函数接口概念 流和收集器基本概念

      本文是针对于java8引入函数式编程概念以及stream流相关的一些简单介绍 什么是函数式编程?   java程序员第一反应可能会理解成类的成员方法一类的东西 此处并不是这个含义,更接近是数学上的 ...

  5. Java SE 8 的流库学习笔记

    前言:流提供了一种让我们可以在比集合更高的概念级别上指定计算的数据视图.如: //使用foreach迭代 long count = 0; for (String w : words) { if (w. ...

  6. 开源框架】Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发

    [原][开源框架]Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发,欢迎各位... 时间 2015-01-05 10:08:18 我是程序猿,我为自己代言 原文  http: ...

  7. Java SE 8 流库

    1. 流的作用 通过使用流,说明想要完成什么任务,而不是说明如何去实现它,将操作的调度留给具体实现去解决: 实例:假如我们想要计算某个属性的平均值,那么我们就可以指定数据源和属性,然后,流库就可以对计 ...

  8. KiCad 开源元件库收集

    KiCad 开源元件库收集 KiCad 官方 https://gitee.com/KiCAD-CN (国内镜像) https://github.com/kicad Digikey KiCad 元件库 ...

  9. Java SE 8 流库(一)

    1. 流的作用 通过使用流,说明想要完成什么任务,而不是说明如何去实现它,将操作的调度留给具体实现去解决: 实例:假如我们想要计算某个属性的平均值,那么我们就可以指定数据源和属性,然后,流库就可以对计 ...

随机推荐

  1. pyqt信号和槽传递额外参数

    转载:fengyu09 环境:python2.7.8 —— pyqt 4.11.1 使用Pyqt编程过程中,经常会遇到给槽函数传递额外参数的情况.但是信号-槽机制只是指定信号如何连接到槽,信号定义的参 ...

  2. webscoket通信初步(一)

    只要动手做起来,多投入时间和精力.耐心去研究,以大多人的智商加google,平时遇到的大部分问题我们都是可以自己解决的,大部分的知识我们都是可以掌握的. 我们都知道http协议是单向请求的,无法实现双 ...

  3. 关于Strategy和State设计模式

    之前,我在描述我所采用的设计模式时,一直在Strategy和State之间犹豫,略微有些拿捏不准,说哪种设计模式好.结果到最后,会根据自己所想,觉得是State就是State,觉得Strategy就是 ...

  4. kubernetes k8s yum localinstall

    localinstall 是安装在本地的rpm包顺便解决依赖关系 yum localinstall docker-common-1.12.6-68.gitec8512b.el7.centos.x86_ ...

  5. go中的map[Interface{}]Interface{}理解

    map里面的k,v支持很多的类型.对于go来说也是,go中有个接口的概念,任何对象都实现了一个空接口.那么我们把map里面的k,v都用interface去定义,当我们在使用这个map的时候,我们可以把 ...

  6. 谷歌获取chromium

    转自:http://blog.sina.com.cn/s/blog_496be0db0102voit.html 先参看 http://www.chromium.org/developers/how-t ...

  7. win7开始菜单路径

    按Win + R, 输入C:\Users\zhouwanchun\AppData\Roaming\Microsoft\Windows\Start Menu 点击确定

  8. ODBC数据源管理器-》系统DSN-》没有....Microsoft Access Driver(*mdb,*,accdb)

    问题如标题: 解决方法:打开目录:“C:\Windows\SysWOW64”,双击该目录下的“odbcad32.exe”文件,就进去ODBC数据源管理界面了,现在这个界面中就有access的驱动了!

  9. javascript-保留2位小数函数方法

    function zero(num){ var str=num.toString(); if(str.indexOf(".")==-1){ return num+'.00'; }e ...

  10. ZooKeeper系列(7):ZooKeeper一致性原理

    一.ZooKeeper 的实现 1.1 ZooKeeper处理单点故障 我们知道可以通过ZooKeeper对分布式系统进行Master选举,来解决分布式系统的单点故障,如图所示. 图 1.1 ZooK ...