Predicate
Predicate接收一个参数,返回一个布尔值,用来进行判断是否符合条件
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
来看个例子
//获取集合中大于2的数字
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
list.stream().filter(item->item>2).forEach(System.out::println);
这里 filter接收的参数就是Predicate
如果想要获取集合中大于5的偶数该怎么办呢,看下面的例子:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> p1 = item -> item % 2 == 0;
Predicate<Integer> p2 = item -> item > 5;
list.stream().filter(p1.and(p2)).collect(Collectors.toList()).forEach(item -> System.out.println(item));
Supplier
Supplier不传入参数,返回一个值,这种结构很适合作为工厂来产生对象
@FunctionalInterface
public interface Supplier<T> {
T get();
}
例子:
Supplier<Student> supplier = () -> new Student();
Student student = supplier.get();
Student student2 = supplier.get();
System.out.println(student); //com.test.Student@6e8cf4c6
System.out.println(student2);//com.test.Student@12edcd21
可以看出每次get都得到一个新的对象
Optional
Optional是为了解决NullPointerException而提出来的
/**
* A container object which may or may not contain a non-null value.
* If a value is present, {@code isPresent()} will return {@code true} and
* {@code get()} will return the value.
*
* @since 1.8
*/
public final class Optional<T> {
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
of
of方法传入的参数不能为null。如果传入参数为null,则抛出NullPointerException 。
Optional<String> optional = Optional.of("hello");
optional.ifPresent(value -> System.out.println(value)); //hello
ofNullable
ofNullable方法可以传null,如果为null,则返回一个空的Optional。
Optional<String> optional = Optional.ofNullable(null);
optional.ifPresent(System.out::print);//这里不会打印出东西
map
如果一个对象本身不为null,但是他内部的对象可能为null,这时就可以用map来判断
Employee employee = new Employee();
employee.setName("zhangsan");
Employee employee2 = new Employee();
employee2.setName("lisi");
Company company = new Company();
company.setName("company1");
List<Employee> employeeList = Arrays.asList(employee, employee2);
company.setList(employeeList);
Optional<Company> optional = Optional.ofNullable(company);
System.out.println(optional.map(company1 -> company1.getList()).orElse(Collections.emptyList()));
网友评论