Java8内置的四大核心函数式接口

package java8.Lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
* Java8内置的四大核心函数式接口
*
* 1.Consumer<T>:消费型接口
* void accept(T t);
* 2.Supplier<T>:供给型接口
* T get();
* 3.Function<T, R>:函数型接口
* R apply(T t);
* 4.Predicate<T>:断言型接口
* boolean test(T t);
*/
public class TestLambda3 {

public static void main(String[] args) {
//Consumer<T>消费型接口
happy(10000, (m) -> System.out.println("Play Game!: " + m + " yuan"));

//Supplier<T>
List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
for (Integer num : numList) {
System.out.println(num);
}

//Function<T, R>函数型接口
String newStr = strHandler("\t\t\t 你牛逼 ", (str) -> str.trim());
System.out.println(newStr);

String subStr = strHandler("我也牛逼,大家都牛逼", (str) -> str.substring(2, 5));
System.out.println(subStr);

//Predicate<T> 断言型接口
List<String> list = Arrays.asList("Hello", "you", "me", "Java", "Scala");
List<String> newlist = filterStr(list, (s) -> s.length() > 3);
for (String str : newlist) {
System.out.println(str);
}
}

private static void happy(double money, Consumer<Double> con) {
con.accept(money);
}

//需求:产生一些整数,并放入集合中
private static List<Integer> getNumList(int num, Supplier<Integer> sup) {
List<Integer> list = new ArrayList<>();

for (int i = 0; i < num; i++) {
Integer n = sup.get();
list.add(n);
}

return list;
}

//需求:用于处理字符串
private static String strHandler(String str, Function<String, String> fun) {
return fun.apply(str);
}

//需求:将满足条件的字符串放入集合中去
private static List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> strList = new ArrayList<>();

for (String str : list) {
if (predicate.test(str)) {
strList.add(str);
}
}

return strList;
}

}



回到顶部