首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Java8/lambda执行嵌套的'if‘语句?

如何使用Java8/lambda执行嵌套的'if‘语句?
EN

Stack Overflow用户
提问于 2015-07-26 01:40:28
回答 3查看 55.5K关注 0票数 23

我有以下代码,我想用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());
EN

回答 3

Stack Overflow用户

发布于 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");
    }
};
票数 5
EN

Stack Overflow用户

发布于 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());
票数 1
EN

Stack Overflow用户

发布于 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());

请参阅http://ideone.com/EOBiEP

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31629324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档