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

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("aa");
arrayList.add("aA");
arrayList.add("bbb");
arrayList.add("a1c2");
arrayList.add("a1a");
arrayList.add("c"); Supplier<Stream<String>> supplier = ()->arrayList.stream();

直接输出结果

/***
* 直接输出结果
*/
//1. iterator()相关 ->旧式迭代器
//(1)iterator
System.out.println("----直接输出结果--旧式迭代器-----start--");
Iterator<String> iterator = arrayList.stream().parallel().iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(); //forEachRemaining()
arrayList.iterator().forEachRemaining((x)->System.out.println(x.toString()));
System.out.println("----直接输出结果--旧式迭代器-----end--");
System.out.println(); //(2) spliterator()
Spliterator<String> spliterator = arrayList.stream().spliterator();
while(spliterator.tryAdvance((n)->System.out.println(n))){}
System.out.println(); spliterator = arrayList.stream().spliterator();
spliterator.forEachRemaining((n)->System.out.println(n));
System.out.println(); Spliterator<String> spliterator2 = arrayList.stream().spliterator().trySplit();
spliterator2.forEachRemaining((n)->System.out.println(n));
spliterator2.forEachRemaining((n)->System.out.println(n));
System.out.println(); //2. forEach() ->parallel()返回的结果顺序不确定
System.out.println("----直接输出结果--.stream().parallel().forEach()-----start--");
arrayList.stream().parallel().forEach(n->System.out.println(n));
System.out.println("----直接输出结果--.stream().parallel().forEach()-----end--");
System.out.println(); //3. forEachOrdered() ->parallel()返回的结果顺序与流中的顺序相同
System.out.println("----直接输出结果--.stream().parallel().forEachOrdered()-----start--");
arrayList.stream().parallel().forEachOrdered(n->System.out.println(n));
System.out.println("----直接输出结果--.stream().parallel().forEachOrdered()-----end--");
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();

简单的计算

//1. count()	数量
System.out.println(supplier.get().count());
System.out.println(); //2. max() 最大数值
System.out.println(supplier.get().max(String::compareToIgnoreCase).orElse(""));
System.out.println(); //3. min() 最小数值
System.out.println(supplier.get().min(String::compareToIgnoreCase).orElse(""));
System.out.println(); //4. findFirst(), 非空集合中第一个
//一般结合filer()==>findFirst==>找到匹配条件中第一个
String findFirstValue = supplier.get().findFirst().orElse("");
System.out.println(findFirstValue); findFirstValue = supplier.get().filter(x->x.length()>2).findFirst().orElse("");
System.out.println(findFirstValue); findFirstValue = supplier.get().filter(x->x.length()>2).sorted().findFirst().orElse("");
System.out.println(findFirstValue); findFirstValue = supplier.get().filter(x->x.length()>2).sorted(Comparator.comparing(String::length).thenComparing(String::compareTo).reversed()).findFirst().orElse("");
System.out.println(findFirstValue);
System.out.println(); //5. findAny(), 非空集合中任意一个
//一般结合filer()==>findAny==>找到匹配任意匹配,表示能够匹配
String findAnyValue = supplier.get().filter(x->x.length()>4).findAny().orElse("");
System.out.println(!findAnyValue.equals(""));
System.out.println(); //6. anyMatch(), 任意元素有无匹配
//直接使用看是否有匹配
boolean anyMatch = supplier.get().anyMatch(x->x.length()>3);
System.out.println(anyMatch);
System.out.println(); //7. allMatch(), 所有元素有无匹配
//直接使用看是否有匹配
boolean allMatch = supplier.get().allMatch(x->x.length()>0);
System.out.println(allMatch);
System.out.println(); //8. noneMatch(), 没有任意元素有无匹配
//直接使用看是否有匹配
boolean noneMatch = supplier.get().noneMatch(x->x.length()>4);
System.out.println(noneMatch);
System.out.println();

收集到映射表中

/***
* 收集到映射表中
*/
//1.toArray()
System.out.println("----收集到数据结构中--.stream().toArray()-----start--");
String[] stringArray = arrayList.stream().toArray(String[]::new);
System.out.println(Arrays.toString(stringArray));
System.out.println(); System.out.println(Arrays.toString(arrayList.stream().toArray()));
System.out.println("----收集到数据结构中--.stream().toArray()-----end--");
System.out.println(); //2.collect() 收集元素到集合, 总和/平均值/最大/最小值
ArrayList<NamePhoneEmail> myList = new ArrayList<>();
myList.add(new NamePhoneEmail("Larry", "555-5555", "Larry@HerbSchildt.com"));
myList.add(new NamePhoneEmail("James", "555-4444", "James@HerbSchildt.com"));
myList.add(new NamePhoneEmail("Mary", "555-3333", "Mary@HerbSchildt.com")); //(1) toList() 使用Collectors.toList()
System.out.println("----收集到数据结构中--.stream().map().collect(.toList()).forEach()-----start-------");
myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(Collectors.toList()).forEach(n->System.out.println(n.name+" "+n.phonenum));
System.out.println(); //在循环之前先做map()处理
myList.stream().map((a) -> a.toString()).collect(Collectors.toList()).forEach(System.out::println);
System.out.println("----收集到数据结构中--.stream().map().collect(.toList()).forEach()-----end-------");
System.out.println();
System.out.println(); //(2) toSet() 使用Collectors.toSet()
System.out.println("----收集到数据结构中--.stream().map().collect(.toSet()).forEach()-----start-------");
myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(Collectors.toSet()).forEach(n->System.out.println(n.name+" "+n.phonenum));
System.out.println("----收集到数据结构中--.stream().map().collect(.toSet()).forEach()-----end-------");
System.out.println();
System.out.println(); //(3) ->TreeSet 使用Collectors.toCollection() TreeSet自动排序
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(TreeSet::new)).forEach()-----start-------");
TreeSet<String> toTreeSet = arrayList.stream().collect(Collectors.toCollection(TreeSet::new));
toTreeSet.forEach(n->System.out.println(n));
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(TreeSet::new)).forEach()-----end-------");
System.out.println();
System.out.println(); //(4) ->ArrayList 使用Collectors.toCollection()
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(ArrayList::new)).forEach()-----start-------");
ArrayList<String> toArrayList = arrayList.stream().collect(Collectors.toCollection(ArrayList::new));
toArrayList.forEach(n->System.out.println(n));
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toCollection(ArrayList::new)).forEach()-----end-------");
System.out.println();
System.out.println();
System.out.println();
System.out.println(); //(5) ->toMap 收集到映射表中 //1) 指定keyMapper和valueMapper
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper)).forEach()-----start-------");
Map<String, String> toMap = myList.stream().collect(
Collectors.toMap(
NamePhoneEmail::getName, //keyMapper
NamePhoneEmail::getPhonenum //valueMapper
));
toMap.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper)).forEach()-----end-------");
System.out.println();
System.out.println(); //2) 指定keyMapper, valueMapper, mergeFunction
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction)).forEach()-----start-------");
Stream<Locale> localesStream = Stream.of(Locale.getAvailableLocales());
//通过指定的mergeFunction, 解决冲突
Map<String, String> languageNames = localesStream.collect(
Collectors.toMap(
Locale::getDisplayLanguage, //keyMapper
l->l.getDisplayLanguage(l), //valueMapper
(existingValue, newValue)->existingValue //mergeFunction, 合并两个 keyMapper 相同的值
)); languageNames.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction)).forEach()-----end-------");
System.out.println(); System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper(Set), mergeFunction)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<String, Set<String>> countryLanguageSets = localesStream.collect(
Collectors.toMap(
Locale::getDisplayCountry, //keyMapper
l -> Collections.singleton(l.getDisplayLanguage()), //valueMapper Returns an immutable set containing only the specified object
(a, b) -> { // union of a and b //mergeFunction
Set<String> union = new HashSet<>(a);
union.addAll(b);
return union;
}
));
countryLanguageSets.entrySet().forEach((n)->System.out.println(n.getKey()+" "+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(Collectors.toMap(keyMapper, valueMapper(Set), mergeFunction)).forEach()-----end-------");
System.out.println();
System.out.println(); //(6) to LinkedList
System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to LinkedList---start-------");
LinkedList<NamePhone> nkList = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(
()->new LinkedList<>(),
(list, element) -> list.add(element),
(listA, listB)->listA.addAll(listB)
);
nkList.forEach(n->System.out.println(n.name+" "+n.phonenum));
System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to LinkedList---end-------");
System.out.println();
System.out.println(); //(7) to HashSet
System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to HashSet---start-------");
HashSet<NamePhone> hsSet = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum)).collect(
HashSet::new,
HashSet::add,
HashSet::addAll
);
hsSet.forEach(n->System.out.println(n.name+" "+n.phonenum));
System.out.println("----收集到数据结构中--.stream().collect(supplier, accumulator, combiner)--to HashSet---end-------");
System.out.println();
System.out.println(); //(8)总和, 平均值, 最大值, 最小值
ArrayList<Integer> integerList = new ArrayList<>();
integerList.add(23);
integerList.add(66);
integerList.add(888);
integerList.add(999);
integerList.add(1024); //总和
Integer integerCollect = integerList.stream().collect(Collectors.summingInt(Integer::intValue));
System.out.println(integerCollect); //总和, 数目, 平均值, 最大值, 最小值
IntSummaryStatistics intSummaryStatistics = integerList.stream().collect(Collectors.summarizingInt(Integer::intValue));
System.out.println(intSummaryStatistics.getSum());
System.out.println(intSummaryStatistics.getCount());
System.out.println(intSummaryStatistics.getAverage());
System.out.println(intSummaryStatistics.getMax());
System.out.println(intSummaryStatistics.getMin());
System.out.println("------intSummaryStatistics-------"); ArrayList<Long> longList = new ArrayList<>();
longList.add(23l);
longList.add(66l);
longList.add(888l);
longList.add(999l);
longList.add(1024l); Long longCollect = longList.stream().collect(Collectors.summingLong(Long::longValue));
System.out.println(longCollect); LongSummaryStatistics longSummaryStatistics = longList.stream().collect(Collectors.summarizingLong(Long::longValue));
System.out.println(longSummaryStatistics.getSum());
System.out.println(longSummaryStatistics.getCount());
System.out.println(longSummaryStatistics.getAverage());
System.out.println(longSummaryStatistics.getMax());
System.out.println(longSummaryStatistics.getMin());
System.out.println("------longSummaryStatistics-------"); ArrayList<Double> doubleList = new ArrayList<>();
doubleList.add(23.2);
doubleList.add(66.3);
doubleList.add(888.5);
doubleList.add(999.6);
doubleList.add(1024.8); Double doubleCollect = doubleList.stream().collect(Collectors.summingDouble(Double::doubleValue));
System.out.println(doubleCollect); DoubleSummaryStatistics doubleSummaryStatistics = doubleList.stream().collect(Collectors.summarizingDouble(Double::doubleValue));
System.out.println(doubleSummaryStatistics.getSum());
System.out.println(doubleSummaryStatistics.getCount());
System.out.println(doubleSummaryStatistics.getAverage());
System.out.println(doubleSummaryStatistics.getMax());
System.out.println(doubleSummaryStatistics.getMin());
System.out.println("------doubleSummaryStatistics-------"); //(9) joining() 指定连接符
System.out.println("----收集到数据结构中--.stream().collect(Collectors.joining())-----start-------");
String collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining());
System.out.println(collectJoining); //指定连接符
collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining(";"));
System.out.println(collectJoining); //指定连接符, 前缀, 后缀
collectJoining = myList.stream().map((a) -> a.email).collect(Collectors.joining(";","prefix "," suffix"));
System.out.println(collectJoining);
System.out.println("----收集到数据结构中--.stream().collect(Collectors.joining())-----end-------");
System.out.println();
System.out.println();

群组和分组
/***
* 群组和分组
*/ //1. groupingBy() //1)直接使用 groupingBy() 按指定元素分组
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<String, List<Locale>> countryToLocalsMap = localesStream.collect(Collectors.groupingBy(Locale::getCountry));
countryToLocalsMap.entrySet().forEach((n)->{
System.out.print(n.getKey()+":");
n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
System.out.println();
});
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element)).forEach()-----end-------");
System.out.println();
System.out.println(); //2) groupingBy后toList, 和直接使用.groupingBy(element) 结果相同
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toList)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<String, List<Locale>> groupingByToList = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.toList()));
groupingByToList.entrySet().forEach((n)->{
System.out.print(n.getKey()+":");
n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
System.out.println();
});
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toList)).forEach()-----end-------");
System.out.println();
System.out.println(); //3) groupingBy后toSet
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toSet)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<String, Set<Locale>> groupingByToSet = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.toSet()));
groupingByToSet.entrySet().forEach((n)->{
System.out.print(n.getKey()+":");
n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
System.out.println();
});
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingBy(element, toSet)).forEach()-----end-------");
System.out.println();
System.out.println();
System.out.println(); //4) groupingByConcurrent() 得到一个并行映射表
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingByConcurrent(element)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
countryToLocalsMap = localesStream.collect(Collectors.groupingByConcurrent(Locale::getCountry));
countryToLocalsMap.entrySet().forEach((n)->{
System.out.print(n.getKey()+":");
n.getValue().forEach(locale->System.out.print(locale.getDisplayLanguage()+","));
System.out.println();
});
System.out.println("----收集到数据结构中--.stream().collect(Collectors.groupingByConcurrent(element)).forEach()-----end-------");
System.out.println();
System.out.println();
System.out.println(); //a) groupingByConcurrent后toList, 和直接使用.groupingByConcurrent(element) 结果相同
//b) groupingByConcurrent后toSet //5)使用partitioningBy() 按照指定条件(true or false)分组
System.out.println("----收集到数据结构中--.stream().collect(Collectors.partitioningBy(Predicate<? super T> predicate)).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<Boolean, List<Locale>> booleanLocalesStream = localesStream.collect(Collectors.partitioningBy((Locale l)->l.getCountry().equals("CN")));
List<Locale> trueList = booleanLocalesStream.get(true);
System.out.println("trueList "+trueList); List<Locale> falseList = booleanLocalesStream.get(false);
System.out.println("falseList "+falseList); System.out.println("----收集到数据结构中--.stream().collect(Collectors.partitioningBy(Predicate<? super T> predicate)).forEach()-----end-------");
System.out.println();
System.out.println();
System.out.println(); //a) partitioningBy后toList, 和直接使用.partitioningBy(element) 结果相同
//b) partitioningBy后toSet
下游收集器
/***
* 下游收集器
*/ ArrayList<City> cityArrayList = new ArrayList<>();
cityArrayList.add(new City("AAA", "0001", 1234, 1234, 1234.1));
cityArrayList.add(new City("ABA", "0001", 4321, 4321, 4321.2)); cityArrayList.add(new City("BAA", "0002", 1004, 1004, 1004.6));
cityArrayList.add(new City("BBA", "0002", 1034, 1034, 1034.8)); //1. counting() //在groupingBy(), groupingByConcurrent(), partitioningBy()之后, 处理下游(接下来)的值
//1) Collectors.counting() 计算收集到的元素个数
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), counting()).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<String, Long> countryToLocalsCountMap = localesStream.collect(Collectors.groupingBy(Locale::getCountry, Collectors.counting()));
countryToLocalsCountMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), counting()).forEach()-----end-------");
System.out.println();
System.out.println(); System.out.println("----收集到数据结构中--.stream().collect(groupingByConcurrent(), counting()).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
ConcurrentMap<String, Long> countryToLocalsConcurrentCountMap = localesStream.collect(Collectors.groupingByConcurrent(Locale::getCountry, Collectors.counting()));
countryToLocalsConcurrentCountMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(groupingByConcurrent(), counting()).forEach()-----end-------");
System.out.println();
System.out.println(); System.out.println("----收集到数据结构中--.stream().collect(partitioningBy(), counting()).forEach()-----start-------");
localesStream = Stream.of(Locale.getAvailableLocales());
Map<Boolean, Long> booleanLocalesMap = localesStream.collect(Collectors.partitioningBy((Locale l)->l.getCountry().equals("CN"), Collectors.counting()));
System.out.println("trueList count:"+booleanLocalesMap.get(true));
System.out.println("falseList count:"+booleanLocalesMap.get(false)); booleanLocalesMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , counting:"+n.getValue())); System.out.println("----收集到数据结构中--.stream().collect(partitioningBy(), counting()).forEach()-----end-------");
System.out.println();
System.out.println(); //2. Collectors.summing() 计算收集到的元素的和 System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingInt()).forEach()-----start-------");
Map<String, Integer> collectCitySummingIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingInt(City::getIntPopulation)));
collectCitySummingIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingInt:"+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingInt()).forEach()-----end-------");
System.out.println();
System.out.println(); System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingLong()).forEach()-----start-------");
Map<String, Long> collectCitySummingLongMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingLong(City::getLongPopulation)));
collectCitySummingLongMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingLong:"+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingLong()).forEach()-----end-------");
System.out.println();
System.out.println(); System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingDouble()).forEach()-----start-------");
Map<String, Double> collectCitySummingDoubleMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.summingDouble(City::getDoublePopulation)));
collectCitySummingDoubleMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , summingDouble:"+n.getValue()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), summingDouble()).forEach()-----end-------");
System.out.println();
System.out.println(); //3. Collectors.maxBy() 计算收集到的元素的最大值 传入比较器
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), maxBy()).forEach()-----start-------");
Map<String, Optional<City>> collectCityMaxIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.maxBy(Comparator.comparing(City::getIntPopulation))));
collectCityMaxIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , getIntPopulation maxBy:"+n.getValue().get().getIntPopulation()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), maxBy()).forEach()-----end-------");
System.out.println();
System.out.println(); //4. Collectors.minBy() 计算收集到的元素的最小值
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), minBy()).forEach()-----start-------");
Map<String, Optional<City>> collectCityMinIntMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.minBy(Comparator.comparing(City::getIntPopulation))));
collectCityMinIntMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , getIntPopulation minBy:"+n.getValue().get().getIntPopulation()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), minBy()).forEach()-----end-------");
System.out.println();
System.out.println(); //5. Collectors.mapping() ** 两层操作,第一遍groupby(), 第二遍再mapping()
//两层操作,第一层,按照getState分组后;第二层,拿getName得最大
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), mapping()).forEach()-----start-------");
Map<String, Optional<String>> collectCityMaxStatusMap = cityArrayList.stream().collect(Collectors.groupingBy(City::getState, Collectors.mapping(City::getName, Collectors.maxBy(String::compareTo))));
collectCityMaxStatusMap.entrySet().forEach((n)->System.out.println(n.getKey()+" , collectCityMaxStatusMap maxBy:"+n.getValue().get()));
System.out.println("----收集到数据结构中--.stream().collect(groupingBy(), mapping()).forEach()-----end-------");
System.out.println();
System.out.println(); //可以调用min()
约简操作 reduce()

/***
* 约简操作 reduce() 从流中计算值
*
* V1 op V2 op V3 ... op VN
*
* 约简操作中, 流中元素的顺序不能有限制,
* 可以应用于约简操作的: 求和, 乘积, 字符串连接,求最大值, 求最小值, 求集合的并和交
* 不可应用于约简操作的: 减法, 除法
*/ List<Integer> integerValues = Arrays.asList(11,22,33,44,55,66); //1. 简单的示例
//求和, 最大值, 最小值
Optional<Integer> sumOptional = integerValues.stream().reduce(Integer::sum);//(x,y) -> (x+y)
if(sumOptional.isPresent()){
System.out.println(sumOptional.get());
} Optional<Integer> maxOptional = integerValues.stream().reduce(Integer::max);
if(maxOptional.isPresent()){
System.out.println(maxOptional.get());
} Optional<Integer> minOptional = integerValues.stream().reduce(Integer::min);
if(minOptional.isPresent()){
System.out.println(minOptional.get());
} Optional<Integer> multiplyOptional = integerValues.stream().reduce((x,y)->(x*y));
if(multiplyOptional.isPresent()){
System.out.println(multiplyOptional.get());
} //2. 传入初始值(幺元值), 作为计算的起点 stream()
//T reduce(T identity, BinaryOperator<T> accumulator)
//identity只在第一次使用
/**
a:1 b:11
a:11 b:22
a:242 b:33
a:7986 b:44
a:351384 b:55
a:19326120 b:66
1275523920
*/
Integer reduce = integerValues.stream().reduce(1, (a,b)->{
System.out.println("a:"+a+" b:"+b);
return a+b;
});
System.out.println(reduce); //3. 传入初始值(幺元值), 作为计算的起点; parallelStream()
//<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
//identity每次都会使用, 和accumulator结合使用时
//combiner用来处理accumulator的结果
//使用stream()时combiner不起作用; 只有parallelStream() 并行流 时combiner才起作用
Integer reduce2 = integerValues.parallelStream().reduce(
1,
(a,b)->{
System.out.println("a+b a:"+a+" b:"+b);
return a+b;
},
(a,b)->{
System.out.println("a*b a:"+a+" b:"+b);
return a*b;
}
);
System.out.println(reduce2);

辅助类

class City{
private String name;
private String state;
private int intPopulation;
private long longPopulation;
private double doublePopulation; public City(String name, String state, int intPopulation, long longPopulation, double doublePopulation) {
this.name = name;
this.state = state;
this.intPopulation = intPopulation;
this.longPopulation = longPopulation;
this.doublePopulation = doublePopulation;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getState() {
return state;
} public void setState(String state) {
this.state = state;
} public int getIntPopulation() {
return intPopulation;
} public void setIntPopulation(int intPopulation) {
this.intPopulation = intPopulation;
} public long getLongPopulation() {
return longPopulation;
} public void setLongPopulation(long longPopulation) {
this.longPopulation = longPopulation;
} public double getDoublePopulation() {
return doublePopulation;
} public void setDoublePopulation(double doublePopulation) {
this.doublePopulation = doublePopulation;
} } class NamePhoneEmail {
String name;
String phonenum;
String email; NamePhoneEmail(String n, String p, String e) {
name = n;
phonenum = p;
email = e;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPhonenum() {
return phonenum;
} public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} @Override
public String toString() {
return "name:"+name+",phonenum:"+phonenum+",email:"+email;
}
} class NamePhone {
String name;
String phonenum; NamePhone(String n, String p) {
name = n;
phonenum = p;
}
}











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. 廖雪峰Java1-4数组操作-4多维数组

    二维数组 二维数组就是元素为数组的数组 二维数组每个数组的长度不要求一样.比如 int[][] = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } } int[][] ...

  2. navicat for mysql 最简便的破解方法

    Navicat 破解工具 1.安装Navicat软件 安装成功之后进行破解. 然后选择刚刚安装的Navicat安装路径下找到navicat.exe文件,点击选择即可激活 成功.  (注意此步骤解析的是 ...

  3. [UE4]增加开枪冷却时间, Get Time Seconds

    Get Time Seconds:游戏开始到现在过去了多少秒

  4. log4j自带的两个类MDC和NDC作用以及用途

    原文转载至: https://blog.csdn.net/joeyon/article/details/52982330 要想实现获取IP并显示在log中必须先了解log4j自带的两个类MDC和NDC ...

  5. Keepalived+Nginx+tomcat实现系统的高可用

    Keepalived+Nginx+tomcat实现系统的高可用 1:安装vmware虚拟机 2:安装linux系统,我自己下载的centos6.5 3:安装JDK,tomcat 解压tomcat到/u ...

  6. uigrid配置详解(1)

    $scope.gridOptions.rowTemplate = '<div style="background-color: aquamarine" ng-click=&q ...

  7. system调用导致子进程socket句柄泄漏问题分析

    问题引出:A进程与B进程各自独立,都是服务器进程,常驻系统,互不相干.在某次重启A进程后,发现由于固定监听的端口被占用而无法启动.检查,发现是B进程占用了该端口,检查B进程代码,没有相关的打开该固定端 ...

  8. CRM 权限内可查看的记录数

    CREATE FUNCTION dbo.fn_GetFilteredIdsSqlString ( ) , ) , ) ) RETURNS NVARCHAR(max) AS BEGIN ) SET @s ...

  9. easyUI的combotree的树的懒加载。

    var tree=[{    "id":1,    "text":"My Documents",    "children&quo ...

  10. cordova 常用操作

    #创建插件 plugman create --name MyMath --plugin_id SimpleMath --plugin_version #进入插件目录 cd MyMath #plugin ...