lambda -> if else

Posted dingwen_blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lambda -> if else相关的知识,希望对你有一定的参考价值。

尝试使用lambda表达式替代多分支语句,优化代码。补充一点,在JDK1.9中有类似的实现。如Optional中的ifPresentOrElse()方法。相当于

if (val != null{
	// 执行操作
}else {
// 执行操作
}

尝试自己实现if else

OptionalConsumer定义


package demo;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 函数式编程实现if else
 *
 * @author dingwen
 * 2021.06.04 09:33
 */
public class OptionalConsumer<T> implements Consumer<Optional<T>> {

    private final Consumer<T> ifAction;
    private final Runnable elseAction;
    private Predicate<Optional<T>> condition = Optional::isPresent;

    public OptionalConsumer(Consumer<T> ifAction, Runnable elseAction) {
        super();
        this.ifAction = ifAction;
        this.elseAction = elseAction;
    }

    public OptionalConsumer(Consumer<T> ifAction, Runnable elseAction, Predicate<Optional<T>> condition) {
        super();
        this.ifAction = ifAction;
        this.elseAction = elseAction;
        this.condition = condition;
    }

    public static <T> OptionalConsumer<T> of(Consumer<T> ifAction, Runnable elseAction) {
        return new OptionalConsumer<T>(ifAction, elseAction);
    }

    public static <T> OptionalConsumer<T> of(Consumer<T> ifAction, Runnable elseAction, Predicate<Optional<T>> condition) {
        return new OptionalConsumer<T>(ifAction, elseAction, condition);
    }

    @Override
    public void accept(Optional<T> t) {
        if (condition.test(t)) {
            t.ifPresent(ifAction);
        } else {
            elseAction.run();
        }
    }

    @Override
    public Consumer<Optional<T>> andThen(Consumer<? super Optional<T>> after) {
        Objects.requireNonNull(after);
        return (Optional<T> t) -> {
            accept(t);
            after.accept(t);
        };
    }
}

使用


package demo;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 判断逻辑不太对等待完善
 *
 * @author dingwen
 * 2021.06.04 10:12
 */
public class OptionalConsumerTest {
    static String flag = "";

    public static void main(String[] args) {
        String test = "dding";

        // if  ding  1
        // else if ding 2
        // else if null 3
        // else if not null 4
        Predicate<Optional<String>> condition = opt -> opt.isPresent() && opt.get().equalsIgnoreCase("ding");
        Consumer<Optional<String>> consumer1 = OptionalConsumer.of((str) -> testIf(), OptionalConsumerTest::testElse,condition);
        Consumer<Optional<String>> consumer2 = OptionalConsumer.of((str) -> testElseIf1(), OptionalConsumerTest::testElseIf2);
        consumer1.andThen(consumer2).accept(Optional.of(test));
        System.out.println(flag);
    }

    public static void testIf() {
        flag = "1";
    }

    public static void testElse() {
        flag = "2";
    }

    public static void testElseIf1() {
        flag = "3";
    }

    public static void testElseIf2() {
        flag = "4";
    }
}

多分支采用function替换


package demo;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 使用function解决多分支
 *
 * @author dingwen
 * 2021.06.04 10:58
 */
public class FunctionDemo2 {
    private final Map<String, Function<String, String>> map = new HashMap<>();

    public String append(String appendType) {
        init();
        Function<String, String> function = map.get(appendType);
        return function.apply(appendType);
    }

    public void init() {
        map.put("1", val -> {
            System.out.println("实行了分支1");
            return "1" + "分支1";
        });

        map.put("2", val -> {
            System.out.println("执行了分支2");
            return "2" + "分支2";
        });

        map.put("3", val -> {
            System.out.println("执行分支3");
            return "3" + "分支3";
        });

        map.put("4", val -> {
            System.out.println("执行分支4");
            return "4" + "分支4";
        });
    }

    public static void main(String[] args) {
        FunctionDemo2 functionDemo2 = new FunctionDemo2();
        functionDemo2.init();
        System.out.println(functionDemo2.append("2"));
        System.out.println(functionDemo2.append("1"));
    }
}

以上是关于lambda -> if else的主要内容,如果未能解决你的问题,请参考以下文章

JDK1.8新特性Lambda表达式简化if-else里都有for循环的优化方式

if / if - else / else with lambda expression [closed]

lambda 中if-elif-if

20个简洁的 JS 代码片段

pandas(Dataframe)里使用lambda匿名函数if..else表达式

向 lambda 函数添​​加多个表达式,以获取 if/else 输出