package com.my.lambda;
import org.junit.jupiter.api.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;
/**
* @author: creat
* @date: 2021/6/17 23:47
* Java 8内置4个函数式接口
* 1.Consumer<T> 消费型接口 void accept();
* 2.Supplit<T> 供给型接口 T get();
* 3.Function<T,R> 函数型接口 R apply(T R);
* 4.Predicate<T> 断言型接口 boolean test(T t);
* @description:
*/
public class TestLambda {
@Test
public void testConsumer(){
happy(1000,(m)-> System.out.println("消费:"+ m +" 元"));
}
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
@Test
public void testSuppliter(){
List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
numList.stream().forEach(num-> System.out.println(num));
}
//需求,产生指定个数的整数,并放入集合中
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;
}
@Test
public void testFunction(){
String newStr=strHandler("\t\t\t wqhueowh ",(str)->str.trim());
System.out.println(newStr);
String s = strHandler("486484erwwer652", str -> str.substring(5, 10));
System.out.println(s);
}
//需求,用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}
@Test
public void testPredicate(){
List<String> list = Arrays.asList("hueroqw","dauiho","3we","rn");
List<String> strList=filterStr(list,s->s.length()>3);
strList.stream().forEach(s-> System.out.println(s));
}
//需求,满足条件的字符串放入集合中
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;
}
}