//java8的4大核心函数式接口//1.Consumer<T>:消费性接口//需求:public void happy(double money, Consumer<Double> consumer){ consumer.accept(money);}@Testpublic void test(){ happy(1000,(e)-> System.out.println("happy消费了"+ e +"元"));}//2.Supplier<T> 供给型接口//T get();//需求:产生一定数量整数,并放进集合中public List<Integer> getList(int size, Supplier<Integer> supplier){ List<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { Integer num = supplier.get(); list.add(num); } return list;} @Testpublic void test2(){ List<Integer> list = getList(10,()->(int)(Math.random()*100)); for (Integer num : list) { System.out.println(num); }} //3.函数型接口//Function<T,R>//R apply<T t>//需求:去除首尾空格public String strHandler(String str, Function<String,String> fun){ return fun.apply(str);}@Testpublic void test3(){ String strTrim = strHandler("\t\t\txsjifcdsnkjfhs ",(e)->e.trim()); System.out.println(strTrim);}//4.Predicate 断言型接口//boolean test(T t)//将满足条件的字符串放进集合public List<String> getNewList(List<String> list , Predicate<String> pre){ List<String> newList = new ArrayList<>(); for (String str : list) { if(pre.test(str)){ newList.add(str); } } return newList;}@Testpublic void test4(){ List<String> list = java.util.Arrays.asList("adsj","xjsai","sdjasio","ws"); List<String> li = getNewList(list,(s)->s.length()>3); for (String str : li) { System.out.println(str); } }
原文地址:https://www.cnblogs.com/yunqing/p/9221117.html
时间: 2024-11-04 11:47:17