四大内置核心函数式接口
1.Cosumer<T>消费型接口
void accept(T t);
/**
* @Author: 郜宇博
* @Date: 2021/8/31 21:34
* 四大核心内置接口
*/
public class BuiltInInterface {
/**
* 消费型接口
* @param money
* @param consumer
*/
public void happy(int money, Consumer<Integer> consumer){
consumer.accept(money);
}
@Test
public void test(){
happy(100,(Integer money)->{
System.out.println("消费了"+money+"元");
});
}
}
2.Supploer< T> 供给型接口
T get();
@Test
public void test(){
//每次调用供给型接口生产随机数,存储在arrayList中
ArrayList<Integer> arrayList = product(10, ()-> new Random().nextInt(100));
//遍历
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public ArrayList<Integer> product(int count, Supplier<Integer> supplier){
ArrayList<Integer> list = new ArrayList<>();
//生产count次
for (int i = 0; i < count; i++) {
Integer num = supplier.get();
list.add(num);
}
return list;
}
3.Function< T> 函数型接口
R apply(T t);
//函数式接口测试
@Test
public void test3(){
final String oldStr = "\t\t\t你好";
String strHandler = strHandler(oldStr,(str)->str.trim());
System.out.println(oldStr);
System.out.println(strHandler);
}
public String strHandler(String str, Function<String,String> function){
String strHandler = function.apply(str);
return strHandler;
}
4.Predicate< T>断言式接口
boolean test(T t);
@Test
public void test4(){
List<String> list = Arrays.asList("abcd","abd","eww","dsadasdas","12");
//接口实现为字符串长度大于3
List<String> newList = strFilter(list,(str)->str.length()>3);
System.out.println(newList);
}
//断言式接口
public List<String> strFilter(List<String> list, Predicate<String > predicate){
List<String> newStrings = new ArrayList<>();
for(String str: list){
//满足断言条件的加入到新的集合中
if (predicate.test(str)){
newStrings.add(str);
}
}
return newStrings;
}