package com.insightfullogic.java8.answers.chapter3;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

public class FilterUsingReduce {

	public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
		return stream.reduce(new ArrayList<O>(), (acc, x) -> {
			
			List<O> newAcc = new ArrayList<>(acc);
			newAcc.add(mapper.apply(x));
			return newAcc;
			
		}, (List<O> left, List<O> right) -> {
			
			List<O> newLeft = new ArrayList<>(left);
			newLeft.addAll(right);
			return newLeft;
			
		});
	}
}

package com.insightfullogic.java8.answers.chapter3;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

public class FilterUsingReduce {

	public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
		
		// reduceб:(List<O> identity, BiFunction<List<O>, ? super I, List<O>> accumulator, BinaryOperator<List<O>> combiner)
		return stream.reduce(new ArrayList<O>(), (acc, x) -> {
			// mapܵLambdaʽFunctionӿڵһʵ
			// ˴ͨFunctionӿʵֵת,ﵽЧ
			// ÿһβList<O>newAccݸcombinerӿ
			List<O> newAcc = new ArrayList<>(acc);
			newAcc.add(mapper.apply(x));
			return newAcc;
			
		}, (List<O> left, List<O> right) -> {
			// leftΪϴμ㱣List<O>ʼֵΪnew ArrayList<O>()
			// combinerӿڽaccumulatorصֵȫnewLeft
			// ֱӵԭLambda,ֲڼȳʵϱfinal͵
			List<O> newLeft = new ArrayList<>(left);
			newLeft.addAll(right);
			return newLeft;
			
		});
	}
}

add comment for question FilterUsingReduce in chapter3