Java 8将函数列表应用于值列表

时间:2018-07-10 08:51:49

标签: java-8 functional-programming java-stream

任务:我们有一个映射器列表,必须将其应用于参数列表。 我们该怎么办?:

我不是很好的变体:

public static final Function<List<IntUnaryOperator>, UnaryOperator<List<Integer>>> multifunctionalMapper =
    lst -> {
        UnaryOperator<List<Integer>> uOp = new UnaryOperator<List<Integer>>() {
            @Override
            public List<Integer> apply(List<Integer> integers) {
                final int[] curFunct = new int[1];
                List<Integer> newLst = integers;
                for (int i = 0; i < lst.size(); i++) {
                    curFunct[0] = i;
                    newLst = newLst.stream().map(curInt -> lst.get(curFunct[0]).applyAsInt(curInt)).collect(Collectors.toList());
                }
                return newLst;
            }
        };
        return uOp;
    };

映射器列表addOneMuxTwoTransformation:

public static final UnaryOperator<List<Integer>> addOneMuxTwoTransformation =
        multifunctionalMapper.apply(Arrays.asList(x -> x+1, x -> x*2));

测试:

addOneMuxTwoTransformation.apply(Arrays.asList(1,2,3)).stream().forEach(System.out::println);

将打印:

4
6
8

如何减少functionalMapper的代码?

2 个答案:

答案 0 :(得分:2)

这是您要做什么吗?

List<IntUnaryOperator> ops = Arrays.asList(a -> a++, a -> a*2);
IntUnaryOperator reduce = ops.stream().reduce(a -> a, IntUnaryOperator::andThen);

IntStream.of(1, 2, 3).map(reduce).forEach(System.out::println);

答案 1 :(得分:0)

下一个解决方案是

public static final Function<List<IntUnaryOperator>, UnaryOperator<List<Integer>>> multifunctionalMapper =lstFunc->
         lstVals -> lstVals.stream()
        .map(curValue -> lstFunc.stream().reduce(IntUnaryOperator::andThen).orElse(x -> x).applyAsInt(curValue))
        .collect(Collectors.toList());