欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java8时间和lambda表达式用法

程序员文章站 2022-06-04 22:56:05
...

java8时间和lambda表达式用法

//Lambda表达式用法
        List<Integer> list=new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);list.add(8);list.add(9);list.add(10);

        list.stream().filter(a -> a>2 && a<5).forEach(b -> {
            System.out.println(b);
            System.out.println(b+1);
        });//结果3 4 4 5
        list.stream().filter(a -> a<5).limit(2).forEach(b -> System.out.println(b));//结果1 2
        List<Integer> li=new ArrayList<>();
        li=list.stream().filter(a -> a<5).collect(Collectors.toList());
        li.forEach(c -> System.out.println(c));//结果1 2 3 4

        ////时间用法
        java.util.Date date = new java.util.Date();
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault(); //获取当前系统时区
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant,zone);//传统Date转LocalDateTime
        LocalDate localDate = localDateTime.toLocalDate();//获取LocalDate
        LocalTime localTime = localDateTime.toLocalTime();//获取LocalTime
        java.util.Date dates = Date.from(localDateTime.atZone(zone).toInstant());//LocalDateTime转传统Date
        //LocalDateTime类用法
        String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());//格式化获取当前日期字符串
        LocalDateTime datetime = LocalDateTime.parse(nowTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
        System.out.println(datetime);//2019-03-25T17:57:13.073
        System.out.println(datetime.getYear());//获取当前年2019
        System.out.println(datetime.getMonth());//获取当前月MARCH
        System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS").format(LocalDateTime.now()));//2019-03-25 17:57:14:251
        ZonedDateTime zonedDatetime = ZonedDateTime.now(ZoneId.systemDefault());//ZoneId.systemDefault()获取当前系统时区
        System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS").format(zonedDatetime));//2019-03-25 17:57:14:254

        //时间计算
        LocalDateTime from = LocalDateTime.of(2014,Month.APRIL,16,0,0,0);
        LocalDateTime to = LocalDateTime.of(2015,Month.APRIL,16,23,59,59);
        //Duration计算类
        Duration duration = Duration.between(from,to);
        System.out.println( "两个时间相差天数:" + duration.toDays());//365
        System.out.println( "两个时间相差小时数:" + duration.toHours());//8783
相关标签: jdk1.8新特性