使用Vavr进行函数式编程(二)

Option

  • 这个Option(vavr)或Optional(java8)就是提醒开发人员这个值有可能为null,你在使用前进行判空处理。
  • 在Java8中也就是我们上面所描述的Optional。
  • Vavr 中的 Option 与 Java 8 中的 Optional 是相似的。不过 Vavr 的 Option 是一个接口,有两个实现类 Option.Some 和 Option.None,分别对应有值和无值两种情况。Option 也支持常用的 map、flatMap 和 filter 等操作.

/**
 * @author yuanxindong
 * @date 2020/11/18 下午11:24
 */
public class OptionDemo {
  public static void main(String[] args) {
    // vavr 进行操作 vavr的方法相对于Java8的更多一些
    Option<String> str = Option.of("Hello");

    // vavr的几个函数
    String[] es = str.transform((a) -> a.get().split("e"));
    // 使用Map对其进行
    Option<Integer> map = str.map(String::length);
    Option<Integer> integers = str.flatMap(v -> Option.of(v.length()));
    Integer result = integers.isEmpty() ? integers.get() : null;

    // Java8的几个函数
    Optional<String> yes = Optional.of("YES");
    Optional<String> no = yes.map(String::toString);
    String result = no.isPresent() ? no.get() : "no,为null";
  }
}

Either

  • Either 表示可能有两种不同类型的值,分别称为左值或右值。只能是其中的一种情况。
  • Either 通常用来表示成功或失败两种情况。惯例是把成功的值作为右值,而失败的值作为左值。
  • 可以在 Either 上添加应用于左值或右值的计算。应用于右值的计算只有在 Either 包含右值时才生效,对左值也是同理。
package com.yuanxindong.fp.vavr.data;

import io.vavr.control.Either;

import java.util.Random;

/** @author yuanxindong */
public class EitherDemo {
  static Random random = new Random();
  private static double randomMath = random.nextInt(5);

  public static void main(String[] args) {

    Either<String, String> compute = compute();
    System.out.println(compute);

    Either<String, String> eitherLeft =
        compute().map(str -> "输出" + str).left().toEither();

    System.out.println(eitherLeft);

    Either<String, String> eitherRight =
            compute().map(str -> "输出" + str).right().toEither();
    System.out.println(eitherRight);
  }

  private static Either<String, String> compute() {

    return randomMath > 5
            ? Either.left("随机数大于5")
            : Either.right("随机数小于5");
  }
}

Try

  • Try 用来表示一个可能产生异常的计算。
  • Try 接口有两个实现类,Try.Success 和 Try.Failure,分别表示成功和失败的情况。
  • Try.Success 封装了计算成功时的返回值,而 Try.Failure 则封装了计算失败时的 Throwable 对象。
  • Try 的实例可以从接口 CheckedFunction0、Callable、Runnable 或 Supplier 中创建。
  • Try 也提供了 map 和 filter 等方法。值得一提的是 Try 的 recover 方法,可以在出现错误时根据异常进行恢复。
package com.yuanxindong.fp.vavr.data;

import io.vavr.control.Try;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Consumer;

/**
 * @author yuanxindong
 * @date 2020/11/19  上午12:27
 */
public class TryDemo {
    public static void main(String[] args){

        //使用try进行捕获异常,且对异常进行恢复
        Try<Integer> result = Try.of(() -> 1 / 0).recover(e -> 1);
        System.out.println(result);

        //of里面是一个function function异常就会捕获
        Try<String> lines = Try.of(() -> Files.readAllLines(Paths.get("1.txt")))
                .map(list -> String.join(",", list))
                .andThen((Consumer<String>) System.out::println);

        //of里面是一个function
        Try<String> lineResult = Try.of(() -> Files.readAllLines(Paths.get("1.txt")))
                .map(list -> String.join(",", list)).andThen((Consumer<String>) System.out::println);

        
        boolean success = lineResult.isSuccess();

        System.out.println(lineResult);
    }

}

Lazy

  • Lazy 表示的是一个延迟计算的值。
  • 在第一次访问时才会进行求值操作,而且该值只会计算一次。之后的访问操作获取的是缓存的值。
package com.yuanxindong.fp.vavr.data;

import io.vavr.Lazy;

import java.math.BigInteger;

/**
 * @author yuanxindong
 * @date 2020/11/22  下午10:33
 */
public class LazyDemo {
  public static void main(String[] args) {
    //使用lazy将将值缓存到内存中,再次获取的时候可以直接获取
      Lazy<BigInteger> lazy = Lazy.of(() ->
              BigInteger.valueOf(1024).pow(1024));

      //判断是否已经求过值
      System.out.println(lazy.isEvaluated());

      //获取lazy的值
      System.out.println(lazy.get());

      //判断是否有进行计算过
      if(lazy.isEvaluated()){
          //将lazy进行map 再次求绝对值
          BigInteger  abs = lazy.map(t -> t.abs()).get();
      }
      
      System.out.println(lazy.isEvaluated());
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_40413961/article/details/110010580