java函数式编程-vavr

链式极昼
• 阅读 160
public static String join(String... words) {
        System.out.println(List.of(words).mkString("|"));
        return List.of(words)
                .intersperse(",")
                .foldLeft(new StringBuilder(), StringBuilder::append)
                .toString();
    }

    /**
     * 元组最为方便的一种数据结构,将任意类型任意多个数据统一放到一个对象中,无论作为参数传递还是结果返回都可以实现多个不同类型数据的传递
     */
    public static void tupleTest() {
        Tuple2<String, Integer> tuple2 = Tuple.of("1nidd1", 22);
        System.out.println(tuple2._1);
        System.out.println(tuple2._2);
    }

    /**
     * 简介的异常处理,不会因为异常而影响程序的运行,代码也更加简练
     */
    public static void tryTest() {
        Try<Integer> result = Try.of(() -> 1 / 0);
        System.out.println(result.isSuccess());
        Try<Integer> result1 = Try.of(() -> 1 / 1);
        System.out.println(result1.get());

        // Try<Integer> result = Try.of(() -> 1 / 0);

    }

    /**
     * 比java自带的更好用更好理解,
     */
    public static void functionTest() {
        Function0<String> result = () -> NullPointerException.class.getName();
        System.out.println(result.apply());
        Function5<String, String, String, String, String, String> concat =
                (a, b, c, d, e) -> a + b + c + d + e;
        String finalString = concat.apply(
                "Hello ", "world", "! ", "Learn ", "Vavr");
        System.out.println(finalString);
        Function2<Integer, Integer, Integer> sum = Function2.of(Integer::sum);
        System.out.println(sum.apply(2, 13));
    }


    /**
     * 有链表实现的list,具有不可变性,线程安全,每一次prepend都会返回一个新的list,而不会改变原来的list,并且通过toJavaList和java库的list兼容
     */
    public static void listTest() {
        List<Integer> list = List.of(1, 5, 6);
        int sum = list.sum().intValue();
        System.out.println(list.size() + "," + list.length() + "," + sum);
        System.out.println( list.tail().prepend(3).toString());
        sum = list.sum().intValue();
        System.out.println(list.toString());
        System.out.println(list.size() + "," + list.length() + "," + sum);

        List<Integer> list1 = List.of(1, 2, 3);
        List<Integer> list2 = list1.tail().prepend(0);
        System.out.println(list1.toString()+","+list2.toString());
        System.out.println(list2.prepend(39).toString());
        java.util.List list3 = list1.toJavaList();
        list3.add(99);
        System.out.println(list3.toString());

    }

    public static void listTest1() {
        List<Integer> list = List.of(1, 5, 6);
        System.out.println(list.map(v->v+10));
        Function1<Integer, java.util.List> fun = (v)-> {ArrayList arrayList = new ArrayList();
        arrayList.add(v);return arrayList;};
        java.util.List apply = fun.apply(2);
        System.out.println(apply.toString());
        System.out.println(List.of(1, 2, 3).toJavaList(java.util.ArrayList::new).toString());

    }

    /**
     * lazy延迟计算,只有在get时才开始计算
     */
    public static void lazyTest() {
        Lazy<Double> lazy = Lazy.of(Math::random);
        System.out.println(lazy.isEvaluated());
        Double d1 = lazy.get();
        System.out.println(lazy.isEvaluated());
        Double d2 = lazy.get();
        System.out.println(lazy.isEvaluated());
        System.out.println(d1 + "," + d2);
    }

    /**
     * 替代switch case,代码简洁,语义明确
     * @param input
     */
    public static void patternTest( int input) {
        String output = Match(input).of(
                Case($(2), "1"),
                Case($(2), "2"),
                Case($(3), "3"),
                Case($(), "x")
        );
        System.out.println(output);
    }

    /**
     * 替代switch case,代码简洁,语义明确
     * @param input
     */
    public static void patternTest1( int input) {
         Match(input).of(
                Case($(integer -> input>3&&input<8),o-> run(()-> System.out.println("1"))),
                //Case($(2),o-> run(()-> {throw new NullPointerException();})),
                 Case($(2),o-> run(()-> System.out.println("2"))),
                Case($(3),o-> run(()-> System.out.println("3"))),
                Case($(), o->run(()-> System.out.println("x")))
        );
    }
    public static void patternTest2( ) {
        int value = -1;
        Match(value).of(
                Case($(v -> v > 0), o -> run(() -> System.out.println("> 0"))),
                Case($(0), o -> run(() -> System.out.println("0"))),
                Case($(), o -> run(() -> System.out.println("< 0")))
        );
// 输出<  0
    }


    /**
     * 对当前函数调用curried()方法,得到一个当前函数的柯理化函数,可以继续调用该函数的方法
     */
    public static void curry(){
        Function3<Integer, Integer, Integer, Integer> function3 = (v1, v2, v3)
                -> (v3 + v2) * v1;
        int result =
                function3.curried().apply(1).curried().apply(2).curried().apply(2);
        System.out.println(result);
    }

    public static void eitherTest(){
        Either<Integer,String> either = 1==1?Either.left(new Integer(2)):Either.right("dd");
        either.map(String::toString).mapLeft(Integer::intValue);
        System.out.println(either);
    }

    public static void streamTest(){
        Map<Boolean, List<Integer>> booleanListMap = Stream.ofAll(1, 2, 3, 4, 5)
                .groupBy(v -> v % 2 == 0)
                .mapValues(Value::toList);
        System.out.println(booleanListMap);
// 输出 LinkedHashMap((false, List(1, 3, 5)), (true, List(2, 4)))

        Tuple2<List<Integer>, List<Integer>> listTuple2 = Stream.ofAll(1, 2, 3, 4)
                .partition(v -> v > 2)
                .map(Value::toList, Value::toList);
        System.out.println(listTuple2);
// 输出 (List(3, 4), List(1, 2))

        List<Integer> integers = Stream.ofAll(List.of("Hello", "World", "a"))
                .scanLeft(0, (sum, str) -> sum + str.length())
                .toList();
        System.out.println(integers);
// 输出 List(0, 5, 10, 11)

        List<Tuple2<Integer, String>> tuple2List = Stream.ofAll(1, 2, 3)
                .zip(List.of("a", "b"))
                .toList();
        System.out.println(tuple2List);
// 输出 List((1, a), (2, b))

        System.out.println(Stream.range(1,3).filter(i -> i % 2 == 0).asJava().toString());
    }

    public static void queueTest(){
        Queue<Integer> queue = Queue.of(4,5,6,7);
        System.out.println(queue.dequeue()._1);

        System.out.println(queue.enqueue(50));

        System.out.println(Queue.of(1).dequeueOption().get()._1());
    }

    public static void optionTest(){
        Option<String> maybeFoo = Option.of("fdf");
        try {
            System.out.println(maybeFoo.map(s -> s.toUpperCase() + "bar").get());
        } catch (NullPointerException e) {
            // this is clearly not the correct approach
        }
    }



    public static void main(String[] args) {

       // patternTest(2);

       // patternTest(6);

       // System.out.println(join("22","33","44"));

       // tupleTest();

       // tryTest();

      //  functionTest();

      //   listTest();

      //  listTest1();

      //  streamTest();

      //  queueTest();

        optionTest();

      //   curry();

      //   eitherTest();

      //  patternTest1(2);
      //  patternTest1(9);
      //  patternTest2();

//        lazyTest();

//        System.out.println("---------------");

//        lazyTest();
    }
点赞
收藏
评论区
推荐文章
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
4年前
java使用Aspose向word模板写入数据
_Aspose.Words是一个商业.NET类库,可以使得应用程序处理大量的文件任务。Aspose.Words支持Doc,Docx,RTF,HTML,OpenDocument,PDF,XPS,EPUB和其他格式。使用Aspose.Words可以在不使用Microsoft.Word的情况下生成、修改、转换和打印文档。__1、Aspose在ma
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Stella981 Stella981
4年前
Kali Day01
1root@kali:~/文档arpspoofieth0t172.20.151.172.20.151.1234:64:a9:36:4:b70:0:0:0:0:0080642:arpreply172.20.151.1isat34:64:a9:36:4:b7334:64:a9:36:4
Stella981 Stella981
4年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Stella981 Stella981
4年前
Leetcode——Substring with Concatenation of All Word
Youaregivenastring, s,andalistofwords, words,thatareallofthesamelength.Findallstartingindicesofsubstring(s)in s thatisaconcatenationofeachwordin words