欢迎访问yhm138的博客园博客, 你可以通过 [RSS] 的方式持续关注博客更新

MyAvatar

yhm138

HelloWorld!

Java 函数式编程

Java 8 Streams API 详解

写链式调用

参考博客:
https://cloud.tencent.com/developer/article/1591343
https://www.cnblogs.com/dengchengchao/p/11855723.html

//求只出现一次的数字(其余数字出现都是2次)
//比如,求1,2,2,3,3中出现一次的数字
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;



public class Solution {
    /**
     * @param nums: Represents the incoming number
     * @return: A int value representing whether the
     *          return is a palindrome or not
     */
    public int uniqueNumber(int nums[]) {
        // write your code here
        List<Integer> numlist = Arrays.stream(nums).boxed().collect(Collectors.toList());
        int result = numlist.stream().reduce((a,b) -> a ^ b ).get();
        return result;

    }
}

//得到字符串数组的各个字符串长度
import java.util.*;
import java.util.stream.*;


public class Main {
	public static void main(String[] args) {
        List<String> strings = Arrays.asList(
          "abc", "", "bc", "12345",
          "efg", "abcd","", "jkl");
        List<Integer> lengths = strings
          .stream()
          .filter(string -> !string.isEmpty())
          .map(s -> s.length())
          .collect(Collectors.toList());
        lengths.forEach((s) -> System.out.println(s));

	}
}
//求出1~100中所有偶数的和
import java.util.*;
import java.util.stream.IntStream;

public class Main {
	public static void main(String[] args) {
		// write your code here
		int result=IntStream.range(1,100+1)
				.filter(x-> x%2==0)
				.reduce(0,(a,b)->a+b);
		System.out.println("Even sum of 1 - 100: "+result);
	}
}
//韩信点兵,三人一组余两人,五人一组余三人,七人一组余四人,请问最少需要多少士兵。
//无脑解法,直接暴力
import java.util.*;
import java.util.stream.IntStream;

public class Main {
	public static void main(String[] args) {
		// write your code here
		IntStream.range(1,1000000000)
			.filter(x-> (x%3==2&&x%5==3&&x%7==4))
			.findFirst()
			.ifPresent(e -> System.out.println(e));
	}
}
//"[1, 2, 3]"这样的字符串转 int[]
import java.util.*;

public class Solution {
    public int[] arrayConversion(String str) {
        // -- write your code here --
        int [] a = Arrays.stream(str.substring(1,str.length()-1).split(", "))
            .mapToInt(Integer::parseInt)
            .toArray();
        return a;
    }
}
//数组去重后求和
//下面这种写法贼慢
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {

    public int getSum(int arr[]) {
        List<Integer> list1 = Arrays.stream(arr).boxed().collect(Collectors.toList());
        List<Integer> newList = list1.stream()
                          .distinct()
                          .collect(Collectors.toList());
        return newList.stream()
                      .reduce(0,(a,b)->a+b);                  
    }
}
//java8 stream求平均值,最大值,最小值,求和
 
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class Calculate {
 
    public static void main(String[] args) {
        /*
         * 不允许list中存在为空的值,不然会异常
         */
        List<Double> list = Arrays.asList(0D, 1D, 1.2, 5.6);
        List<Integer> integers = Arrays.asList(0, 1, 2, 56);
        Double avg = list.stream().collect(Collectors.averagingDouble(Double::doubleValue));
        Double avgs = list.stream().mapToDouble(Double::doubleValue).average().orElse(0D);
        Double intAvg = integers.stream().mapToInt(Integer::intValue).average().orElse(0D);
        Double min = list.stream().min(Double::compareTo).get();
        Double max = list.stream().max(Double::compareTo).get();
        Double sum = list.stream().mapToDouble(Double::doubleValue).sum();
        Double sums = list.stream().reduce(Double::sum).get();
    }
}

借助Java8实现柯里化

Java中的柯里化看起来是没有语法糖的,至少我没有找到。。。

参考博客:
https://www.jianshu.com/p/c623b8b2aec8 里面提到了4种方式实现柯里化

import java.util.*;
import java.util.function.*;


public class Main {
    public static void main(String[] args) {
        IntFunction<IntFunction<IntUnaryOperator>> f = x -> y -> z -> (x + y) * z;
        IntFunction<IntUnaryOperator> g = f.apply(4);
        IntUnaryOperator mulBy9 = g.apply(5);

        System.out.println(mulBy9.applyAsInt(6)); //54
    }
}

使用Vavr

参考:
https://zhuanlan.zhihu.com/p/194317390 VAVR:颠覆你的 Java 体验-知乎
https://www.jianshu.com/p/f0106fb32404 Java8+ 函数库Vavr简介-简书

posted @ 2022-01-07 14:10  yhm138  阅读(53)  评论(0编辑  收藏  举报