【问题标题】:Java 8 apply list of functions on list of valuesJava 8 在值列表上应用函数列表
【发布时间】:2018-07-10 08:51:49
【问题描述】:

任务:我们有映射器列表,它必须应用于参数列表。 我们该怎么做?:

我不太好的变种:

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

如何减少多功能Mapper的代码?

【问题讨论】:

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


    【解决方案1】:

    这是你想要做的吗?

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

    【讨论】:

    • 但是每次,你需要一个函数,你需要生成,CustomOps 和 CustomReduce。我的解决方案 ONCE Reduce,然后每次实施 CustomOps。请参阅“下一个解决方案是”——即 OnceReduce。
    【解决方案2】:

    下一个解决方案是

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

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2021-09-20
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多