JAVA8函数式接口
java8 中内置的四大核心函数接口
*
* Consumer<T> :消费型接口
* void accept(T t)
* Supplier<T> :供给型接口
* T get()
*
* Function<T,R>:函数型接口
* R apply(T t)
* Predicate<T> :断言型接口
* boolean test(T t)
package airycode_java8.nice4; import org.junit.Test; 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 中内置的四大核心函数接口 * * Consumer<T> :消费型接口 * void accept(T t) * Supplier<T> :供给型接口 * T get() * * Function<T,R>:函数型接口 * R apply(T t) * Predicate<T> :断言型接口 * boolean test(T t) * Created by admin on 2019/1/2. */ public class TestLambda { @Test public void test1(){ happy(10000,(m)-> System.out.println("大保健,每次消费"+m)); } @Test public void test2(){ getNumList(10,()-> (int)(Math.random()*100)); } //函数型接口 @Test public void test3(){ String result = handler("aa", (str) -> str.toUpperCase()); System.out.println(result); } //断言型接口 @Test public void test4(){ List<String> list = Arrays.asList("Hello","AA","CCCC"); List<String> resultList = filterStr(list, (str) -> str.length() > 3); for (String str:resultList) { System.out.println(str); } } //需求:我要将满足条件的字符串放入集合中 public List<String> filterStr(List<String> list, Predicate<String> pre){ List<String> result = new ArrayList<>(); for (String str:list) { if (pre.test(str)) { result.add(str); } } return result; } //需求:用于处理字符串 public String handler(String string, Function<String,String> fun){ return fun.apply(string); } public void happy(double money, Consumer<Double> consumer){ consumer.accept(money); } public List<Integer> getNumList(int num, Supplier<Integer> supplier){ List<Integer> result = new ArrayList<>(); for (int i=0;i<num;i++) { Integer n = supplier.get(); result.add(n); } return result; } }