我有以下代码,我想用lambda函数来实现它,只是为了好玩。可以使用基本的聚合操作来完成吗?
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
if (10 % i == 0) {
result.add(i);
if (i != 5) {
result.add(10 / i);
}
}
}
使用lambda:
List<Integer> result = IntStream.rangeClosed(1, 10)
.boxed()
.filter(i -> 10 % i == 0)
// a map or forEach function here?
// .map(return 10 / i -> if i != 5)
.collect(Collectors.toList());
发布于 2015-07-26 01:44:21
您可以为lambda声明一个body。例如:
Runnable run = () -> System.out.println("Hey");
可能是
Runnable run = () -> {
System.out.println("Hey");
};
在该主体中,您可以创建嵌套语句:
Runnable run = () -> {
int num = 5;
if(num == 5) {
System.out.println("Hey");
}
};
发布于 2015-07-26 02:14:29
您可以这样做:
List<Integer> result1 = IntStream
.rangeClosed(1, 10)
.boxed()
.filter(i -> 10 % i == 0)
.map(i -> (i != 5 ? Stream.of(i, 10 / i) : Stream.of(i)))
.flatMap(Function.identity())
.collect(Collectors.toList());
发布于 2015-07-26 02:06:52
尝试使用flatMap
List<Integer> result = IntStream.rangeClosed(1, 10)
.boxed()
.flatMap((i) -> {
List<Integer> results = new ArrayList<>();
if (10 % i == 0) {
results.add(i);
if (i != 5) {
results.add(10 / i);
}
}
return results.stream();
})
.collect(Collectors.toList());
https://stackoverflow.com/questions/31629324
复制相似问题