Java函数式编程神器 VAVR(vavr - turns java™ upside down)

在这里插入图片描述

什么是函数式编程

  1. 基本概念:他是一种编程范式,对于函数式编程来说,它只关心定义输入数据和输出数据相关的关系,数学表达式里面其实是在做一种映射(mapping),输入的数据和输出的数据关系是什么样的,是用函数来定义的。
  2. 特征:
    • stateless:函数不维护任何状态。函数式编程的核心精神是 stateless,简而言之就是它不能存在状态,打个比方,你给我数据我处理完扔出来。里面的数据是不变的。
    • immutable:输入数据是不能动的,动了输入数据就有危险,所以要返回新的数据集。(不可变的)

Java为什么要函数式编程

  1. 优势
    • 没有状态就没有伤害。
    • 并行执行无伤害。
    • Copy-Paste 重构代码无伤害。
    • 函数的执行没有顺序上的问题。

问题所在

  • 函数式相对于普通的java变成来说,如果没有用过就会直接不清楚这个函数是干什么的,这个是干什么的,如果在团队中只有部分人使用,那我们在其他人在理解我们的代码上就会有问题,也就回增加学习成本,和开发成本。
  • 使用的问题:问题排查的问题 和异常的捕获的问题。

EXAMPLE

package Vavr;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.istack.internal.FragmentContentHandler;
import io.vavr.CheckedFunction0;
import io.vavr.Function1;
import io.vavr.Function2;
import io.vavr.Function3;
import io.vavr.Lazy;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.control.Either;
import io.vavr.control.Option;
import io.vavr.control.Try;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Generated;
import lombok.Getter;

/**
 * 函数式编程demo
 *
 * @author yuanxindong
 * @date 4/17/21  7:30 PM
 */
public class VavrTest {

    /**
     * 元组的使用
     */
    public static void tupleTest() {

        //of 静态方法支持使用
        Tuple2<String, Integer> tuple2 = Tuple.of("Hello", 100);

        Tuple2<String, Integer> updatedTuple2 = tuple2.map(String::toUpperCase, v -> v * 5);

        String result = updatedTuple2.apply((str, number) -> String.join(", ",
            str, number.toString()));

        System.out.println(result);
    }

    /**
     * function函数的使用
     */
    public static void functionTest() {

        // 函数定义,前3个是入参,最后是R
        Function3<Integer, Integer, Integer, Integer> function3 = (v1, v2, v3) -> (v1 + v2) * v3;

        // 函数的组合
        Function3<Integer, Integer, Integer, Integer> composed =
            function3.andThen(v -> v * 100);

        //执行结果
        int result = composed.apply(1, 2, 3);

        System.out.println(result);

        //还有包含部分函数的应用
        Function1<Integer, Integer> function1 = function3.apply(1, 2);

        Integer apply = function1.apply(1);
        System.out.println(apply);

        //项目联想
        //结合项目场景使用比如说PDT中定义几个 函数比如:计算MP时效的函数,计算ALG的函数时效,在定义一些函数结果的拼接等
    }

    /**
     * 柯里化想要解决的问题: 柯里化方法的使用 柯里化的含义: 柯里化(currying)是与λ演算相关的重要概念。通过柯里化,可以把有多个输入的函数转换成只有一个输入的函数,从而可以在λ演算中来表示。 柯里化的名称来源于数学家 Haskell Curry。 Haskell Curry 是一位传奇性的人物,以他的名字命令了 3 种编程语言,Haskell、Brook 和 Curry。
     * 柯里化是把有多个输入参数的求值过程,转换成多个只包含一个参数的函数的求值过程。 对于清单 6 的函数 f(a, b, c),在柯里化之后转换成函数 g,则对应的调用方式是 g(a)(b)(c)。 函数 (x, y) -> x + y 经过柯里化之后的结果是 x -> (y -> x + y)。
     */
    public static void curriedTest() {
        //设置函数 v1 v
        Function3<Integer, Integer, Integer, Integer> function3 = (v1, v2, v3) -> (v1 + v2) * v3;

        //可以看出来是返回来了一个函数
        Function1<Integer, Function1<Integer, Integer>> apply = function3.curried().apply(1);

        //多次柯里化后就会返回我们想要的记过
        int result = function3.curried().apply(1).curried().apply(2).curried().apply(3);
        System.out.println(result);
    }

    /**
     * 记忆化方法 会将之前计算过的方法进行存储,相同参数在第二次调用的时候会使用缓存
     */
    public static void memoized() {

        //计算差方
        Function2<BigInteger, Integer, BigInteger> pow = BigInteger::pow;
        //记忆化
        Function2<BigInteger, Integer, BigInteger> memoized = pow.memoized();

        long start = System.currentTimeMillis();
        memoized.apply(BigInteger.valueOf(1024), 1024);
        long end1 = System.currentTimeMillis();

        memoized.apply(BigInteger.valueOf(1024), 1024);
        long end2 = System.currentTimeMillis();
        System.out.printf("%d ms -> %d ms", end1 - start, end2 - end1);
    }

    /**
     * java  8 中的optional  是类似 其目的都是为了避免NPE的出现
     */
    public static void optionTest() {
        //个人觉得option好用的地方在于这个of 静态函数。
        Option<String> str = Option.of("Hello");

        str.map(String::length);
        //使用对应的值
        Option<Integer> integers = str.flatMap(v -> Option.of(v.length()));
        boolean empty = integers.isEmpty();
        System.out.println(integers);
    }

    /**
     * either 的使用 包含两个值,left(异常值) 和 right(正确值)
     */
    public static void eitherAndTryTest() {

        //这个是
        Either<String, String> either =
            compute()
                .map(str -> str + " World")
                .mapLeft(Throwable::getMessage);
        System.out.println(either);

        //Try的使用,不用写过多的catch,左后将left值交给某一个函数统一处理,
        //在pdt中有很多这样的代码,try catch 嵌套起来使用 包含参数定义的参数校验异常
        //
        Fruit.fromColor("1111");


    }

    private static ThreadLocalRandom random = ThreadLocalRandom.current();

    private static Either<Throwable, String> compute() {
        return random.nextBoolean()
            ? Either.left(new RuntimeException("Boom!"))
            : Either.right("Hello");
    }

    @Getter
    public enum Fruit {

        APPLE("APPLE", "BLACK"),
        BANANA("BANANA", "BLUE"),

        NONE("ORANGE", "WHITE");
        private final String name;
        private final String color;

        Fruit(String name, String color) {
            this.name = name;
            this.color = color;
        }

        public static Fruit fromColor(String color) {

            return Try.of(() -> Arrays.stream(Fruit.values())
                .filter(t -> t.getColor().equals(color))
                .findFirst().orElse(NONE))
                .toEither().getOrElse(NONE);
        }

    }


    /**
     * Lazy 表示的是一个延迟计算的值。在第一次访问时才会进行求值操作,而且该值只会计算一次。之后的访问操作获取的是缓存的值。 Lazy.of 从接口 Supplier 中创建 Lazy 对象。方法 isEvaluated 可以判断 Lazy 对象是否已经被求值。
     */
    public static void LazyTest() {
        Lazy<BigInteger> lazy = Lazy.of(() ->
            BigInteger.valueOf(1024).pow(1024));

        System.out.println(lazy.isEvaluated());
        System.out.println(lazy.get());
        System.out.println(lazy.isEvaluated());
        System.out.println(lazy.get());
        System.out.println(lazy.isEvaluated());
        Lazy<BigInteger> lazy2 = Lazy.of(() ->
            BigInteger.valueOf(1024).pow(1024));
        System.out.println(lazy2.isEvaluated());
        System.out.println(lazy2.get());

        //未想到应用场景
    }


    public static void main(String[] args) {
        tupleTest();
        functionTest();
        curriedTest();
        memoized();
        LazyTest();
    }

}
  • 14
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
As the author of computer books, I spend a lot of time lurking in the computer section of bookstores, observing the behavior of readers while I’m pretending to read the latest issue of Soap Opera Digest magazine. Because of my research, I’ve learned that if you have picked up this book and turned to this introduction, I only have 13 more seconds before you put it down and head to the coffee bar for a double-tall-decaf-skim-with-two-shots-of-vanilla-hold-the-whip latte. So I’ll keep this brief: Computer programming with Java is easier than it looks. I’m not supposed to tell you that because thousands of programmers have used their Java skills to get high-paying jobs in software development, server programming, and Android app creation. The last thing any programmer wants is for the boss to know that anyone with persistence and a little free time can learn this language, the most popular programming language on the planet. By working your way through each of the one-hour tutorials in Sams Teach Yourself Java in 24 Hours, you’ll be able to learn Java programming quickly. Anyone can learn how to write computer programs, even if you can’t program a DVR. Java is one of the best programming languages to learn because it’s a useful, powerful, modern technology that’s embraced by companies around the world. This book is aimed at non-programmers, new programmers who think they hate this stuff, and experienced programmers who want to get up to speed swiftly with Java. It uses Java 9, the latest and greatest version of the language. Java is an enormously popular programming language because of the things it makes possible. You can create programs that feature a graphical user interface, connect to web services, run on an Android phone or tablet, and more. This language turns up in some amazing places. One of them is Minecraft, the gaming phenomenon written entirely in Java. (In this book you learn how to create Java programs that run in that game alongside creepers and zombie pigmen!) This book teaches Java programming from the ground up. It introduces the concepts in English instead of jargon with step-by-step examples of working programs you will create. Spend 24 hours with this book and you’ll be writing your own Java programs, confident in your ability to use the language and learn more about it. You also will have skills that are becoming increasingly important—such as Internet computing, graphical user interface design, app creation, and object-oriented programming. These terms might not mean much to you now. In fact, they’re probably the kind of thing that makes programming seem intimidating and difficult. However, if you can use a computer to create a photo album on Facebook, pay your taxes, or work an Excel spreadsheet, you can learn to write computer programs by reading Sams Teach Yourself Java in 24 Hours.
Learn the basics of Java 9, including basic programming concepts and the object-oriented fundamentals necessary at all levels of Java development. Author Kishori Sharan walks you through writing your first Java program step-by-step. Armed with that practical experience, you’ll be ready to learn the core of the Java language. Beginning Java 9 Fundamentals provides over 90 diagrams and 240 complete programs to help you learn the topics faster. The book continues with a series of foundation topics, including using data types, working with operators, and writing statements in Java. These basics lead onto the heart of the Java language: object-oriented programming. By learning topics such as classes, objects, interfaces, and inheritance you’ll have a good understanding of Java’s object-oriented model. The final collection of topics takes what you’ve learned and turns you into a real Java programmer. You’ll see how to take the power of object-oriented programming and write programs that can handle errors and exceptions, process strings and dates, format data, and work with arrays to manipulate data. This book is a companion to two other books also by Sharan focusing on APIs and advanced Java topics. What You’ll Learn Write your first Java programs with an emphasis on learning object-oriented programming in Java Work with data types, operators, statements, classes and objects Handle exceptions, assertions, strings and dates, and object formatting Use regular expressions Work with arrays, interfaces, enums, and inheritance Deploy Java applications on memory-constrained devices using compact profiles Take advantage of the new JShell REPL tool Who This Book Is For Those who are new to Java programming, who may have some or even no prior programming experience.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值