Consumer<T> 消费型接口
void accept(T t)
@Test
public void consumer1() {
happy(10000, (m) -> System.out.println("消费" + m + "元"));
}
public void happy(double money, Consumer<Double> consumer) {
consumer.accept(money);
}
Supplier<T> 供给型接口
T get()
@Test
public void supplier1() {
List<Integer> numList = getNumList(() -> (int) (Math.random() * 100));
numList.forEach(num -> System.out.println(num));
}
public List<Integer> getNumList(Supplier<Integer> supplier) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(supplier.get());
}
return list;
}
Function<T,R> 函数型接口
R apply(T t)
@Test
public void function1() {
int length = getLength("baozi", (str) -> str.length());
System.out.println(length);
}
public Integer getLength(String str, Function<String, Integer> function) {
Integer length = function.apply(str);
return length;
}
Predicate<T> 断言型接口
boolean test(T t)
@Test
public void predicate1() {
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
List<String> result = filterStr(list, (str) -> str.length() > 3);
result.forEach(r -> System.out.println(r));
}
public List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> strs = new ArrayList<>();
list.forEach(str -> {
if (predicate.test(str)) {
strs.add(str);
}
});
return strs;
}