分类:简单计算, 收集到映射表中 , 群组和分组, 下游收集器, 约简操作 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;
	}
}






























posted on 2018-01-30 00:11  刘达人186  阅读(132)  评论(0编辑  收藏  举报