首页 > 解决方案 > Java 8 apply list of functions on list of values

问题描述

Task: we`ve got list of mappers, which must be applied on list of arguments. How we can do?:

My not really good variant:

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;
    };

list of mappers addOneMuxTwoTransformation:

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

test:

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

will print:

4
6
8

How can be multifunctionalMapper's code reduced?

标签: java-8functional-programmingjava-stream

解决方案


这是你想要做的吗?

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);

推荐阅读