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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 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; } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步