package com.wuzhixin.java8;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSOutput;
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;
/**
* java 8 内置的四大核心接口
*
*
* Consumer<T> :消费型接口
* void accept(T t) 对参数t 进行处理
*
* Supplier<T> :供给型接口
* T get();
*
* Function<T,R>: 函数式接口
*
* R apply (T t)
*
* Predicate<T>: 断言型接口
*
* boolean(T t)
*/
public class TestLamdba3 {
//comsumer <T> 消费型接口
@Test
public void testConsumer(){
test(new Employee(22,"SFSFS",214.143),t-> System.out.println(t.getSalary()));
}
public void test(Employee employee,Consumer<Employee> consumer){
consumer.accept(employee);
}
//Supplier <T> 供给型接口,比如需求 模拟数据裤返回employee 集合
@Test
public void test2(){
List<Employee> employees = get(4, () ->
new Employee((int) Math.random()*100, new Random().nextInt(2) - '0' + "", Math.random())
);
for (Employee employee : employees) {
System.out.println(employee);
}
}
public List<Employee> get(int num, Supplier<Employee> supplier){
List<Employee> employees = new ArrayList<>();
for (int i = 0; i < num; i++) {
Employee employee = supplier.get();
employees.add(employee);
}
return employees;
}
//函数式接口
@Test
public void testDemo3(){
System.out.println(strHandle("sssss", (s) -> s.toUpperCase()));
}
public String strHandle(String str, Function<String,String> function){
return function.apply(str);
}
//断言型接口
@Test
public void testDemo4(){
String str[] = {"1","222","33","666666","5555"};
List<String> strings = Arrays.asList(str);
List<String> strings1 = filterStr(strings, s -> s.length() >= 4);
for (String s : strings1) {
System.out.println(s);
}
}
// 对满足字符串要求的 入集合
public List<String> filterStr(List<String> strings, Predicate<String> predicate){
ArrayList<String> strings1 = new ArrayList<>();
for (String string : strings) {
if(predicate.test(string)){
strings1.add(string);
}
}
return strings1;
}
}
java8新特性
最新推荐文章于 2024-03-05 10:15:00 发布