class Student{
private String name;
private int grade;
//get set ..
}
List list = new ArrayList<>();
Predicate 判定
public interface Predicate{ // lamda表达式匿名函数修改的test boolean test(T t); // 可以和其他判定条件进行逻辑运算 (还有 or 和 negative 方法) default Predicate and(Predicate super T> other) { Objects.requireNonNull(other); return (t) -> test(t) && other.test(t); } //.. }
filter 过滤
list.stream().filter(i -> i.getGrade() > 60); // 过滤掉不大于0的 Predictgreaterthan = i -> i > 60; Predict smallerthan = i -> i < 80; // 筛选出 大于60 小于80 的学生 list.stream().filter(i->greaterthan.test(i.getGrade()) &&smallerthan.test(i.getGrade())); // 筛选出 大于60 小于80 的分数 list.stream().map(Student::getGrade()).filter(greaterthan.and(smallerthan));
map 转换
list.stream().map(i -> i.getGrade()+5) // 让 55 的同学及格 list.stream().map(Student::getGrade).reduce((sum, i) -> sum + i).get();
flatMap 合并流
Stream.of(Arrays.asList(1,3),Arrays.asList(5,6)). flatMap(a->a.stream());
Collectors 集合
Collectors.joining(",");
Collectors.toList();
Collectors.toSet();
Collectors.toMap(Student::getName(), Function.identity());
public interface Function {
//..
static Function identity() {return t -> t;}
}
Match 条件匹配
boolean anyMatch(Predicate super T> predicate); boolean allMatch(Predicate super T> predicate); boolean noneMatch(Predicate super T> predicate);
min max sum… summaryStatistics
list.map(Student::getName()).mapToInt(Integer::intvalue).summaryStatistics().getAvarage(); //summaryStatistics 包括最大值、最小值、总和、平均值
Consumer
@FunctionalInterface public interface Consumer{ // 用给定方式处理入参 void accept(T t); // 多个处理方式串联 default Consumer andThen(Consumer super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } } Consumer hello = s -> System.out.println("Hello, " + s.getName()); hello.accept(new Student("Ming", 90));
Supplier
@FunctionalInterface public interface Supplier{ // 类似工厂模式 T get(); } Supplier studentSupplier = Student::new; studentSupplier.get();
Optional
Optional notnull = Optional.of("something"); // 如果为空会报错
Optional isnull = Optional.ofNullable(); // 允许为空
notnull.get();
notnull.isPresent();
// Optional不为空,进行相应处理
public void ifPresent(Consumer super T> consumer) {
if (value != null)consumer.accept(value);
}
notnull.orElse("somethingelse"); // value == null ? value : "somethingelse"
notnull.orElseGet(()->"default things"); // 使用其他默认值 参数为 Supplier 类型
notnull.orElseThrow(Exception::new); // 为空则抛出异常



