<java8内置的四大核心函数式接口>
Consumer<T> :消费型接口 void accept(T t);
Supplier<T> :供给型接口 T get();
Function<T,R> :函数型接口 R apply(T t);
Predicate<T> :断言型接口 boolean test(T t);
示例:
public class TestLambda { //Predicate<T> 断言型接口 @Test public void testPredicate() { List<String> list = Arrays.asList("hello", "ad", "www"); List<String> newList = filterStr(list, s -> s.length() >= 3); newList.forEach(System.out::println); } //需求: 将满足条件的字符串添加到集合中 public List<String> filterStr(List<String> list, Predicate<String> pre) { List<String> strList = new ArrayList<>(); for (String str : list) { if (pre.test(str)) { strList.add(str); } } return strList; } //Function<T,R> 函数型接口: @Test public void testFunction() { String str = strHandler("\t\t\t hello world", s -> s.trim()); System.out.println(str); } //需求:处理字符串 public String strHandler(String str, Function<String, String> fun) { return fun.apply(str); } //Supplier<T> 供给型接口 @Test public void testSupplier() { List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100)); for (Integer num : numList) { System.out.println(num); } } //需求:产生一些整数,并放入集合中 public List<Integer> getNumList(int num, Supplier<Integer> sup) { List<Integer> list = Lists.newArrayList(); for (int i = 0; i < num; i++) { Integer n = sup.get(); list.add(n); } return list; } //Consumer<T> : 消费型接口 @Test public void testConsumer() { happy(100, con -> System.out.println("刘剑喜欢看电影,每次消费:" + con + "元")); } public void happy(double money, Consumer<Double> con) { con.accept(money); } }