java8Lambda表达式测试用例
package com.stevenyin.lambda.service;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @FileName: LambdaTest4
* @Author Steven
* @Date: 2021/2/28
*
* Java8中内置的4大函数式接口
* 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 LambdaTest4 {
@Test
public void test(){
consumer("hello world",System.out::print);
}
public void consumer(String str, Consumer<String> consumer){
consumer.accept(str);
}
@Test
public void test2(){
List<Integer> integerList = supplier(5, () ->(new Random().nextInt(100)));
for (Integer integer : integerList) {
System.out.println(integer);
}
}
public List<Integer> supplier(Integer number, Supplier<Integer> sup){
List<Integer> list=new ArrayList<>();
for (int i = 0; i < number; i++) {
Integer n= sup.get();
list.add(n);
}
return list;
}
@Test
public void test3(){
String function = function("hello world", String::toUpperCase);
System.out.println(function);
}
public String function(String str, Function<String,String> function){
return function.apply(str);
}
@Test
public void test4(){
List<String> list= Arrays.asList("abc","hello","mark","aa","str","would");
List<String> stringList = strFilter(list, (str) -> str.length() > 3);
for (String str : stringList) {
System.out.println(str);
}
}
public List<String> strFilter(List<String> stringList, Predicate<String> pre){
List<String> list=new ArrayList<>();
for (String str : stringList) {
if(pre.test(str)){
list.add(str);
}
}
return list;
}
}