Java8-Stream-Termination Operation-Reduction and Collection

reduce

    Combine the elements in the stream in sequence to get a new value

    Three overloaded methods:

    1.Optional<T> reduce(BinaryOperator<T> accumulator);

    2.T reduce(T identity, BinaryOperator<T> accumulator)

  3.<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

    The first two are described in some examples below, but the third one has been studied for a long time and did not understand the meaning. After consulting the data, I found that it is used in the concurrent operation of the stream, and the result formed by the first two parameters of each thread is result. The collection is merged into one. So the third parameter is a BinaryOperator function interface

	//归约
	@Test
	public void test5() {
		//reduce(String identity, BinaryOperator<String> accumulator) 第一个参数相当于起始值 ,第二个参数是二元运算函数接口
		String s1 = custs.stream().map(Cust::getCustName).reduce("", (x,y)->x+","+y).replaceFirst(",", "");
		System.out.println(s1);
		
		System.out.println("###################################");
		//reduce(BinaryOperator<String> accumulator) 参数是二元运算函数接口,因为没有给默认值,所以为了避免使用时空指针异常,返回的是Optional
		Optional<String> opt = custs.stream().map(Cust::getCustName).reduce((x,y)->x+","+y);
		String s2 = opt.get().replaceFirst(",", "");
		/*
		 * 从年龄大于40的人中去操作,filter的结果会为空
		 * Optional<String> opt1 = custs.stream().filter((x)->x.getAge()>40).map(Cust::getCustName).reduce((x,y)->x+","+y);
		 * String s3 = opt1.get().replaceFirst(",", "");
		 * 
		 * 这段代码要返回异常:java.util.NoSuchElementException: No value present
		 * 仿佛并没有多大用处似的,看来需要再去了解一下Optional的使用方法
		 */
		
	}

collect

Collect data sources into corresponding collections or maps after filtering, filtering, etc., or collect their statistical information, such as summation, average value, maximum value, minimum value, number of records, etc.

Pictures from other people's textbooks

Start writing examples. .

	@Test
	public void test6() {
		List<Integer> cl1 = custs.stream().map(Cust::getCustId).collect(Collectors.toList());
		System.out.println(cl1);
		
		System.out.println("###############################");
		//如果收集为SET,则具有排重功能
		Set<Integer> st1 = custs.stream().map(Cust::getCustId).collect(Collectors.toSet());
		System.out.println(st1);
		
		System.out.println("###############################");
		//使用时注意不能有重复的值
		Map<String,Integer> m1 = custs.stream().distinct().collect(Collectors.toMap((x)->x.getCustName(), (x)->x.getAge()));
		System.out.println(m1);
		//这个重载的方法比上面多出来的参数是用来处理冲突数据
		Map<String,Integer> m2 = custs.stream().collect(Collectors.toMap((x)->x.getCustName(), (x)->x.getAge(), (x,y)->x*y));
		System.out.println(m2);
		//在上面方法基础上,还可以把其他Map中的数据合并到结果中
		Map<String,Integer> m3 = custs.stream().collect(Collectors.toMap((x)->x.getCustName(), (x)->x.getAge(), (x,y)->x*y,()->{
			Map<String,Integer> mt = new HashMap();
			mt.put("武磊", 2600000);
			mt.put("郜林", 2200000);
			return mt;
		}));
		System.out.println(m3);
		
		System.out.println("###############################");
		//toConcurrentMap用来并发开发当中,其他2个和toMap用法一致,如果在并发开发中推荐使用toConcurrentMap,效率更高
		ConcurrentMap<String,Integer> m4 = custs.stream().distinct().collect(Collectors.toConcurrentMap((x)->x.getCustName(), (x)->x.getAge()));
		System.out.println(m4);
		
		//将结果收集到想要的集合当中
		LinkedList<String> ll1 = custs.stream().map(Cust::getCustName).limit(3).distinct().collect(Collectors.toCollection(LinkedList::new));
		System.out.println(ll1);
		
		//统计记录数-相当于Oracle的count
		Long lc = custs.stream().collect(Collectors.counting());
		System.out.println(lc);
		
		//统计所有记录的年龄-相当于Oracle的sum
		Long ls = custs.stream().collect(Collectors.summingLong(x->x.getAge()));
		System.out.println(ls);
		
		//求所有记录的年龄的平均值,因为经过除法之后会变成Double,所以即使方式使Long类型,其返回结果是Double
		Double ls1 = custs.stream().collect(Collectors.averagingLong(x->x.getAge()));
		System.out.println(ls1);
		
		//收集统计信息---这个功能包含了常用的统计结果,使用起来很方便,但是如果源数据很多,且使用不到那么多统计结果的话,为了考虑程序效率,还是要什么用什么比较好
		DoubleSummaryStatistics dss = custs.stream().collect(Collectors.summarizingDouble(x->x.getAge()));
		System.out.println(dss.getAverage()+","+dss.getCount()+","+dss.getMax());
		
	}

It's late at night, and doze is coming, and there are several methods left, such as grouping, partitioning, connecting, etc. to write next time

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338643&siteId=291194637