java8的4大核心函数式接口

时间:2021-08-07 22:52:28
//java8的4大核心函数式接口
//1.Consumer<T>:消费性接口
//需求:
public void happy(double money, Consumer<Double> consumer){
consumer.accept(money);
}
@Test
public 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;
} @Test
public 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);
}
@Test
public 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;
}
@Test
public 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);
} }