java8补充——函数式编程、新增时间类函数

1、函数式接口

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

public interface PersonSay {
    void sayMessage(String message);
}
	public static void main(String[] args) {
		PersonSay ps = (message) -> {
			System.out.println("hello" + message);
		};
		ps.sayMessage("辣鸡");
	}
@FunctionalInterface这个注解可以加也可以不加,加上会好点,加了之后如果这个接口里面还有其他的方法,就会报错

2、stream流

分为中间操作和结束操作

foreach处理

map,映射处理,左边映射成右边

filter:过滤用的,过滤之后需要收集collect

sorted:排序:传入两个数,前面数减去后面数——>正序排列 

                                              后面数减去前面数——>倒序排列

distincted:去重。上图有两个120,可以去重处理

reduce:规约,规约之后其实返回的是一个终态

allMatch :所有都要满足才会返回true

anyMatch:任意满足返回true

不用流式处理也可以直接处理数据

正序和倒序处理数据示例:

   public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("hdx", 16),
                new Person("hdx1", 17),
                new Person("hdx2", 19),
                new Person("hdx3", 147),
                new Person("hdx4", 56)
                  );
        //正向排序
        persons.sort(Comparator.comparingInt(p->p.age));
        persons.forEach(System.out::println);
        System.out.println("----------------");
        //倒序
        persons.sort(Comparator.comparingInt(p->-p.age));
        persons.forEach(System.out::println);
    }

输出结果:

Person{name='hdx', age=16}
Person{name='hdx1', age=17}
Person{name='hdx2', age=19}
Person{name='hdx4', age=56}
Person{name='hdx3', age=147}
----------------
Person{name='hdx3', age=147}
Person{name='hdx4', age=56}
Person{name='hdx2', age=19}
Person{name='hdx1', age=17}
Person{name='hdx', age=16}

多添加排序:先按照年龄倒序排列,再按名字顺序排

persons.sort(Comparator.comparingInt(Person::getAge).reversed().thenComparing(Person::getName));

并行流:多核同时进行,如果一台机器上还有别的程序需要跑,不建议用并行流,可能会导致别的服务不可用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值