/** * @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"; } }
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"); } }
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); } }
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()); } }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句