java中Lambda表达式相关的四大内置核心函数式接口

知识点:java8中四大内置核心函数式接口

/**
* 1. Consumer<T>:消费型接口
* void accept(T t);
*
* 2. Supplier<T> :供给型接口
* T get();
*
* 3. Function<T,R>: 函数型接口
* R apply(T t);
*
* 4. Predicate<T>: 断言型接口
* boolean test(T t)
* **/
public class TestLambda {

//1.Consumer<T>:消费型接口 void accept(T t);
@Test
public void test(){
shopping(1000,(x)-> System.out.println("今天购物发了"+x+"元"));
}
public void shopping(double money, Consumer<Double> con){
con.accept(money);
}

//2.Supplier<T> :供给型接口 T get();
@Test
public void test2(){
List<Integer> numList=getNumList(3,()->(int)(Math.random()*10));
for (Integer n:numList
) {
System.out.println(n);
}
}
//产生指定个数的整数,放到集合中并返回
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list=new ArrayList<>();
for (int i=0;i<num;i++){
Integer n=sup.get();
list.add(n);
}
return list;
}


//3.Function<T,R>: 函数型接口 R apply(T t);
@Test
public void test3(){
String newStr= handlerStr("helloworld",(str)->str.substring(3,6));
System.out.println(newStr);
}
//处理字符串
public String handlerStr(String str, Function<String,String> fun){
return fun.apply(str);
}

//4.Predicate<T>: 断言型接口 boolean test(T t)
@Test
public void test4(){
List<String> list= Arrays.asList("idea","eclipse","predicate","function");
List<String> returnList= filterStr(list,(str)->str.length()>4);
for (String str:returnList
) {
System.out.println(str);
}
}
//将满足条件的字符串,放到集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> newList=new ArrayList<>();
for (String str:list
) {
if(pre.test(str)){
newList.add(str);
}
}
return newList;
}
}
posted @ 2020-01-07 10:29  shuaiflying  阅读(857)  评论(0编辑  收藏  举报