jdk8 新特性复习

 Lambda 表达式:

一种特殊的匿名内部类 ,语法更简洁

把函数作为参数进行传递

1、基本语法:

<函数式接口> <变量名> =(参数1,参数2)->{ 方法体};

2、使用事项:

形参列表的数据类型会自动推断

如果形参列表为空,只需保留()

如果形参只有1个,()可以省略,只需要参数的名称即可,如(a,b)

如果方法体中的执行语句只有一句,且无返回值,{}可以省略,若有返回值,在省去{}的同时必须省略return 语句,且执行语句也必须只有一句

     Runnable runnable=new Runnable() {
           @Override
           public void run() {
               System.out.println("...");
           }
       };
        new Thread(()-> { System.out.println("2222"); }).start();

 

函数式接口:

如果一个接口只有一个抽象方法,那么这个接口就是一个函数式接口,这类接口可以直接使用lambda表达式

@FunctionalInterface

这个注解可以检测这个接口是否是函数式接口

 

1、常见的函数式接口:

Consumer (消费型): 有参数,无返回值

   t(t-> System.out.println("金额"+t),1000);


public static void t(Consumer<Double> consumer,double m){
consumer.accept(m);
}

supplier(供给型): 无参数,有返回值

Integer supplier = supplier(() -> 10, 100);


  public static Integer supplier(Supplier<Integer> c,int count){
        int a=10;
        for (int i=0;i<count;i++){
            a++;
        }
        return a;
    }

Function(函数型):有参数,有返回值

String he = fun((s) -> s + "11", "he");




    public static String fun(Function<String,String> f,String h){
        return f.apply(h);
    }

predicate(断言型):有参数,返回类型为布尔

main{
  ArrayList<String> li = new ArrayList<>();
        li.add("adadsad");
        li.add("length");
        List<String> p = p((s) -> {
         return    s.length() > 6;
        }, li);
        System.out.println(p);
    }
 public static List<String> p(Predicate<String> predicate,List<String> list){
        ArrayList<String> li = new ArrayList<>();
        for (String s : list) {
            if(predicate.test(s)==true){
                li.add(s);
            }
        }
        return li;

    }

 

方法引用:

方法引用是lambda表达式的一种简写形式。如果lambda表达式方法体重只是一个调用特定的一级存在的方法,则可以使用方法引用

常见形式:

对象::实例方法

类::静态方法

类::实例方法

类::new

 

Stream流的使用

1、普通遍历集合

 ArrayList<String> li = new ArrayList<>();
        li.add("adadsad");
        li.add("length");
        Stream<String> stream = li.stream();
        stream.forEach(s -> System.out.println(s.length()>6?s:"")); //lambda表达式遍历
        stream.forEach(System.out::println);//方法引用遍历

2、多线程方法遍历集合

  ArrayList<String> li = new ArrayList<>();
        li.add("adadsad");
        li.add("length");

        Stream<String> stringStream = li.parallelStream();
        stringStream.forEach(s -> System.out.println(s));

3、遍历数组

 int arr[] ={1,2,3,4,5};
        IntStream stream = Arrays.stream(arr);
        stream.forEach(s-> System.out.println(s));//lambda表达式遍历
        stream.forEach(System.out::println);//方法引用遍历

 Stream 接口中的of,iterate,generte 方法

OF

Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
        integerStream.forEach(System.out::println);

iterate(迭代流)

//        seed 起始点   第二个参数是表达式    limit是执行次数
          Stream.iterate(0, x -> x + 2).limit(5).forEach(System.out::println);

generte (生成流)

 Stream.generate(()->new Random().nextInt(100)>20?"1":"2").limit(10).forEach(aa-> System.out.println(aa));




IntStream

//        遍历0-10   limit:表示只循环两次    结果为 0,1
//range:是一个开口的方法  只遍历到 0-9
        IntStream.range(0,10).limit(2).forEach(System.out::println);




//        rangeClosed:是一个闭合的方法  表示遍历0-10
        IntStream.rangeClosed(0,10).forEach(System.out::print);

 

 

中间操作

Fileter、Limit、skip、distinct、sorted、Map、parallel

 

1、Fileter过滤

  List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(1,"李四","12"));
        emps.add(new Emp(1,"王五","12"));
        emps.add(new Emp(1,"赵柳","12"));

        emps.stream().filter(emp -> emp.getName().length()>2).forEach(System.out::print);

2、Limit限制

//        Limit限制  只遍历集合前2个数据  
        emps.stream().limit(2).filter(s->s.getName().length()<3).forEach(System.out::println);

3、Skip跳过

//        Skip跳过,顺序跳过两条数据
        emps.stream().skip(2).forEach(System.out::println);

4、distanct去掉重复值(注意要重写hashcode和equals)

//        去重
        emps.stream().distinct().forEach(System.out::println);

5、sorted排序

        List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));
        int arr[] ={1,2,3,4,5};
//        排序数组
        Arrays.stream(arr).sorted().forEach(System.out::print);
//        根据某个键值排序对象   这儿根据id排序
        emps.stream().sorted((e1,e2)->Double.compare(e1.getId(),e2.getId())).forEach(System.out::println);

6、map遍历

//        map遍历
        emps.stream().map(s->s.getName()).forEach(System.out::print);

 

并行流(parallelStream)和串行流(Stream)的区别:

并行,指的是在同一时刻多个任务同时执行,容易出现线程问题。

串行,指的是在同一时间段多个任务交替执行。

当然,并行的执行速度更快,但并行也依赖硬件设置,因为它依赖硬件CPU是多核的场景。并发则不受限制

Stream 用时5秒:

 List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));
        ArrayList<Object> list = new ArrayList<>();
        for (int i=0;i<=5000000;i++){
            list.add(UUID.randomUUID().toString());
        }
        long start=System.currentTimeMillis();
        long count = list.stream().sorted().count();
        System.out.println(count);
        System.out.println((System.currentTimeMillis()-start)/1000+"秒");

parallelStream用时2秒:

List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));
        ArrayList<Object> list = new ArrayList<>();
        for (int i=0;i<=5000000;i++){
            list.add(UUID.randomUUID().toString());
        }
        long start=System.currentTimeMillis();
        long count = list.parallelStream().sorted().count();
        System.out.println(count);
        System.out.println((System.currentTimeMillis()-start)/1000+"秒");

计算最大值,最小值,计数

 int arr[]={2,1,0,11,4};
        int asInt = Arrays.stream(arr).max().getAsInt();//计算最大值,最小值
        long count = Arrays.stream(arr).count(); //统计数量
        System.out.println(asInt);
----------------------------------------------------------------------------

List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));
//        统计集合对象里的ID最大值
        Optional<Emp> max = emps.stream().max((e, e1) -> Integer.compare(e.getId(), e1.getId()));
        System.out.println(max);

终止操作

 

1、reduce :根据指定的计算模型将Stream中的值计算得到一个最终结果

统计集合中年龄之和:

 List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));

        Integer integer = emps.stream().map(a -> Integer.parseInt(a.getAge())).reduce((x, y) -> x + y).get();
        System.out.println(integer);

 

2、获取集合中全部的姓名并且封装为一个List集合

   List<Emp> emps = new ArrayList<>();
        emps.add(new Emp(1,"zhangsan","12"));
        emps.add(new Emp(2,"李四","12"));
        emps.add(new Emp(31,"王五","12"));
        emps.add(new Emp(0,"赵柳","12"));
        emps.add(new Emp(5,"赵柳","12"));

        List<String> collect = emps.stream().map(a -> a.getName()).collect(Collectors.toList());
        collect.stream().distinct().forEach(System.out::print);

 

时间API

本地化日期时间API:

LocalDate: 只获取当前的年月日

LocalTime: 只获取当前的时分秒

LocalDateTime: 获取完整的时间

//------------------获取当前完整的日期---------------- 结果:2020-07-30T21:00:23.573
        LocalDateTime localDate= LocalDateTime.now();//获取当前时间
        System.out.println(localDate);
//        -----------只获取当前的年月日------------- 结果:2020-07-30
        LocalDate now = LocalDate.now();
        System.out.println(now+"...");
//      --------------只获取当前的时分秒------------ 结果:21:00:23.574
        LocalTime now1 = LocalTime.now();
        System.out.println(now1+">>>>>");

 

自定义时间:


//        自定义完整时间
        LocalDateTime.of(2018,12,10,12,30,200);
//        自定义年月日时间
        LocalDate.of(2018,12,10);
//        自定义时分秒时间
        LocalTime.of(12,30,200);

时间转换:

 String time="2018-12-03";
        LocalDate parse = LocalDate.parse(time);//转换为年月日格式
        System.out.println(parse);
        String time1="20:30:20";
        LocalTime parse1 = LocalTime.parse(time1);//转换为时分秒格式
        System.out.println(parse1);
        String time2="2018-12-03-20:30:20";
        LocalDateTime parse2 = LocalDateTime.parse(time2);//转换为完整的时间日期格式格式
        System.out.println(parse2);

给当前日期加时间:

//        给日期加时间  年月日 时分秒  都能加
//        给当前的天数加两天
        LocalDateTime localDateTime = LocalDateTime.now().plusDays(2);
        System.out.println(localDateTime);

给当前日期减时间:

//        给日期加时间  年月日 时分秒  都能减少
//        给当前的天数减两天
        LocalDateTime localDateTime = LocalDateTime.now().minusMonths(2);
        System.out.println(localDateTime);

 

 

时间戳(Instand):

Instand:时间戳

//        获取Instant对象
        Instant now = Instant.now();
        System.out.println(now+"now");
//        获取时间戳
        long epochSecond = now.toEpochMilli();
        System.out.println( epochSecond);

zoneId:时区

//        获取时区
ZoneId.getAvailableZoneIds().forEach((a)->System.out.println(a));

 

Instant,Date,LocalDateTime时间的相互转换

1、Date转换为Instant

//        date 转换为Instand
        Instant instant = new Date().toInstant();
//        获取时间戳
        System.out.println(instant.getEpochSecond());

2、Instant转换为LocalDateTime

//        LocalDateTime转换为Instant   ZoneId.systemDefault():使用默认的时区
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println(localDateTime);

 

3、LocalDateTime转换为instant

//        LocalDateTime转换为Instant
        LocalDateTime now = LocalDateTime.now();
        Instant instant1 = now.atZone(ZoneId.systemDefault()).toInstant();
        System.out.println(instant1);

自定义时间格式(格式化)DateTimeFormatter

时间格式转换成字符

 

//       格式化类:DateTimeFormatte

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(LocalDateTime.now());
        System.out.println(format);

字符转换为时间格式

//        把字符串你转换为时间格式
        LocalDateTime parse = LocalDateTime.parse("2018-12-01 10:11:20",dateTimeFormatter);
        System.out.println(parse);

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xixililicm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值