如何使用 Java 8/lambda 执行嵌套的“if”语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31629324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform nested 'if' statements using Java 8/lambda?
提问by LuckyGuess
I have the following code and would like to implement it using lambda functions just for fun. Can it be done using the basic aggregate operations?
我有以下代码,并想使用 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);
}
}
}
Using 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());
采纳答案by Marko Topolnik
The essential observation here is that your problem involves a non-isomorphictransformation: a single input element may map to zero, one, or two output elements. Whenever you notice this, you should immediately start looking for a solution which involves flatMap
instead of map
because that's the only way to achieve such a general transformation. In your particular case you can first apply filter
for a one-to-zero element mapping, then flatMap
for one-to-two mapping:
这里的基本观察是您的问题涉及非同构变换:单个输入元素可能映射到零、一个或两个输出元素。每当您注意到这一点时,您应该立即开始寻找涉及flatMap
而不是map
因为这是实现这种一般转换的唯一方法的解决方案。在您的特定情况下,您可以先申请filter
一对零元素映射,然后flatMap
申请一对二映射:
List<Integer> result =
IntStream.rangeClosed(1, 10)
.filter(i -> 10 % i == 0)
.flatMap(i -> i == 5 ? IntStream.of(i) : IntStream.of(i, 10 / i))
.boxed()
.collect(toList());
(assuming import static java.util.stream.Collectors.toList
)
(假设import static java.util.stream.Collectors.toList
)
回答by Vince Emigh
You could declare a body for a lambda. For example:
您可以为 lambda 声明一个主体。例如:
Runnable run = () -> System.out.println("Hey");
Could be
可能
Runnable run = () -> {
System.out.println("Hey");
};
Within that body, you can create nested statements:
在该正文中,您可以创建嵌套语句:
Runnable run = () -> {
int num = 5;
if(num == 5) {
System.out.println("Hey");
}
};
回答by Danil Gaponov
Try using flatMap
:
尝试使用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());
回答by Mrinal
You can do this:
你可以这样做:
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());
回答by Mantis
Use flatMap
as you are trying to add elements into the pipeline or a 1-to-many mapping. Map is a one to one mapping.
使用flatMap
与您试图将元素添加到管道或1对多的映射。Map 是一对一的映射。
ArrayList<Integer> result = (ArrayList<Integer>) IntStream.rangeClosed(1, 10)
.boxed()
.filter(i -> 10 % i == 0)
.flatMap((Integer i) -> {return i!=5 ? Stream.of(i, (10/i)):Stream.of(i);})
.collect(Collectors.toList());
This results in the same list as
这导致与相同的列表
ArrayList<Integer> result2 = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
if (10 % i == 0) {
result2.add(i);
if (i != 5) {
result2.add(10 / i);
}
}
}
In case your wondering which way is faster the loop method is ~3 times faster than using streams.
如果您想知道哪种方式更快,则循环方法比使用流快约 3 倍。
Benchmark Mode Cnt Score Error Units
testStreams.Bench.loops avgt 5 75.221 ± 0.576 ns/op
testStreams.Bench.streams avgt 5 257.713 ± 13.125 ns/op