/**
* 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 extends BaseTest {
@Test
public void testConsumer(){
// 消费型接口
sellCar(100,money-> System.out.println(money));
}
@Test
public void testSupplier(){
// 供给型接口
List<Integer> integerPutCollection = createIntegerPutCollection(4, () -> (int) (Math.random() * 100));
integerPutCollection.stream().forEach(System.out::println);
}
@Test
public void testFunction(){
// 函数型接口
String strs = handleString("你好", str -> str + "world");
System.out.println(strs);
}
@Test
public void testPredicate(){
// 断言型接口
List<String> list1 = Arrays.asList("lsj","ldh","wyz");
List<String> list = filterStr(list1, str -> str.contains("l"));
list.stream().forEach(System.out::println);
}
// 将满足条件的字符串放入集合中
public List<String> filterStr(List<String> list,Predicate<String> predicate){
List<String> list1 = new ArrayList<>();
for (String str:list) {
if (predicate.test(str)){
list1.add(str);
}
}
return list1;
}
// 处理字符串
public String handleString(String str,Function<String,String> function){
return function.apply(str);
}
// 产生一些整数,并放入集合中
public List<Integer> createIntegerPutCollection(int num,Supplier<Integer> supplier){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(supplier.get());
}
return list;
}
public void sellCar(double money,Consumer<Double> consumer){
consumer.accept(money);
}
}