java-8 - 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?
解决方案
这是你想要做的吗?
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);
推荐阅读
- audio - 在微控制器(Arduino)中播放音频文件
- java - 如何使用 UWECStudent 正确设置构造函数?
- r - 计算r中数据框中某些行的百分位数
- matlab - 如何在 MATLAB 应用程序设计器中显示来自 simulink 块的视频
- url - 如何在 Yii2 中创建带有破折号的自定义 url?
- java - 如何检查应用程序的方向是否在android上固定
- python - 为什么不能从函数返回打印函数?
- javascript - 在javascript中加载两个图像
- react-data-grid - 将行动态添加到 React-data-grid
- azure-functions - Azure Function 2 - 缺少 using 指令或程序集引用?