栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java8 函数式编程常用方法总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java8 函数式编程常用方法总结

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 other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    //..
}

filter 过滤

list.stream().filter(i -> i.getGrade() > 60); // 过滤掉不大于0的
Predict greaterthan = 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 predicate);
boolean allMatch(Predicate predicate);
boolean noneMatch(Predicate 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 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 consumer) {
    if (value != null)consumer.accept(value);
}

notnull.orElse("somethingelse"); // value == null ? value : "somethingelse"
notnull.orElseGet(()->"default things"); // 使用其他默认值 参数为 Supplier 类型
notnull.orElseThrow(Exception::new); // 为空则抛出异常
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号