Java 8新特性

导读:本篇文章讲解 Java 8新特性,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Java 8新特性

Lambda表达式:

需要函数式接口的支持

​ 若接口中只有一个抽象方法时,就是函数式接口。。

​ @FunctionalInterface注解 ,可以检查是否是函数式接口

基础语法:新的操作符:: “ -> ” lambda操作符

将lambda 拆成俩部分,

左侧:Lambda参数列表

右侧:Lambda表达式中所需要实现的功能 。即Lambda体

变化形势:

语法格式一: 无参数,无返回值

​ ()-> sout

语法格式二:有一个参数,无返回值

​ (X)-> sout(X)

语法格式三:若只有一个参数,那么参数的小括可以不写

​ X -> sout(X)

语法格式四:有两个以上的参数,并且Lambda 体中有多条语句

​ Comparator com = (x,y) -> { System.out.println(“=========”);

return Integer.compare(x,y);

} ;

语法格式五:并且Lambda 体中有一条语句 ,

​ 括 号和 return语句都可以不写

​ Comparator com = (x,y) -> Integer.compare(x,y);

四大核心函数式接口:

1Consumer<T> :消费形接口
       void  accept(T  t)
    
2:Supplier<T> : 供给形接口
       void  get()

3:Function<T, R > :函数型接口   R返回类型,,T参数
       R apply (T  t)
    
4:Predicate <R>  :断言型接口
       boolean test ( T  , t)

方法引用

1:对象 : : 实例方法名

2:类 : : 静态方法名

3:类 : : 实例方法名

构造器引用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PMdVBVeU-1665058647031)(C:\Users\12926\AppData\Roaming\Typora\typora-user-images\1658394373040.png)]

数组引用:

type[] :: new ;

Collectors.toList() 将流中的所有元素导出到一个列表( List )

map 方法可以让我们进行一些流的转化,比如原来流中的元素是 A,通过 map 操作,可以使返回的流中的元素是 B

public void testMap() {
        List<String> list = new ArrayList<String>() {{
            add("1");
            add("2");
            add("3");
        }};
        //通过 map 方法list中元素转化成 小写
        List<String> strLowerList = list.stream()
                .map(str -> str.toLowerCase())
                .collect(Collectors.toList());
    }
  List<String> collect = list.stream()
                // 过滤掉我们希望留下来的值
                // 表示我们希望字符串是 1 能留下来
                // 其他的过滤掉
                .filter(str -> "1".equals(str))
                .collect(Collectors.toList());
        collect.forEach(c -> System.out.println(c));  //遍历List集合的俩种方式
        System.out.println("==========================");

        //遍历List集合的俩种方
        Iterator<String> iterator = collect.iterator();
        if (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println("======"+ next);
        }

MapToInt

MapToDouble

public void testMapToInt() {
        List<String> list = new ArrayList<String>() {{
            add("1");
            add("2");
            add("3");
        }};
        list.stream()
                .mapToInt(s->Integer.valueOf(s))
                // 一定要有 mapToObj,因为 mapToInt 返回的是 IntStream,因为已经确定是 int 类型了
                // 所有没有泛型的,而 Collectors.toList() 强制要求有泛型的流,所以需要使用 mapToObj
                // 方法返回有泛型的流
                .mapToObj(s->s)
                .collect(Collectors.toList());
 
        list.stream()
                .mapToDouble(s->Double.valueOf(s))
                // DoubleStream/IntStream 有许多 sum(求和)、min(求最小值)、max(求最大值)、average(求平均值)等方法
                .sum();
    }

Distinct

distinct 方法有去重的功能:

public void testDistinct(){
        List<String> list = new ArrayList<String>() {{
            add("1");
            add("2");
            add("2");
        }};
        list.stream()
                .map(s -> Integer.valueOf(s))
                .distinct()
                .collect(Collectors.toList());
    }

Sorted

Sorted 方法提供了排序的功能,并且允许我们自定义排序。

stream流的创建

步骤:

1:首先创建stream流,

2:中间对流的操作

3:终止操作

创建流的几种方式:

1:可以通过Collection 系列的集合提供的stream (串行流)或paralleStream(并行流)

ArrayList<String> list = new ArrayList<>();

   Stream<String> stream = list.stream();

2:可以通过Arrays的 静态 stream() 方法。

emp[] emp01 = new  emp[10];
Stream<emp> stream1 = Arrays.stream(emp01);

3:可以通过Stream的 静态方法 —-> of()

Stream<emp> emp011 = Stream.of(emp01);

4:无限流 通过Stream 的 iterate

iterate :
Stream<Integer> stream2 = Stream.iterate(1, (x) -> x + 1);


生成: 
    Stream.generate(() -> Math.random());

Stream流的映射:

Collectors.toList() 将流中的所有元素导出到一个列表( List )

map 方法可以让我们进行一些流的转化,比如原来流中的元素是 A,通过 map 操作,可以使返回的流中的元素是 B

FlatMap:方法可以让我们进行一些流的转化,,返回的结果是一个stream流

stream的排序方式:

sort : 自然排序(Comparable)

​ 定制排序(Comparator)

  list.stream()
                .sorted((e1,e2) -> {
                    if (e1.getAge().equals(e2.getAge())) {
                        return e1.getName().compareTo(e2.getName());
                    }else {
                        return e1.getAge().compareTo(e2.getAge());
                    }
                }).collect(Collectors.toList()).forEach(System.out::println);

Stream 流的查找与匹配:

/**
* stream 流的查找与匹配
* allMatch 查找所有是否匹配的元素
* anyMatch 查找是否有任意一个元素满足当前匹配的元素
* noneMatch 没有一个匹配当前的元素
* findFirst 查找第一个元素
* fingAny 查找任意一个元素
* count 统计 流中元素的总个数
* max 返回流中最大的值
* min 返回流中最小的值
*/

import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test02 {
//    List<emp> list = Arrays.asList(
//            new emp("xiao",22, emp.Status.BUSY),
//            new emp("xia",30, emp.Status.VOCATION),
//            new emp("xialijun",99, emp.Status.BUSY),
//            new emp("xia0",30, emp.Status.FREE)
//    );
//    @Test
//    public void test(){
//        Stream<emp> stream = list.stream().filter(e -> e.getAge() > 20)
//                .limit(2)
//                .distinct().skip(1);
//        stream.forEach(System.out::println);
//    }
//    @Test
//    public void test1(){
        list.stream()
                .map(emp::getName).forEach(System.out::println);
//        list.stream()
//                .sorted((e1,e2) -> {
//                    if (e1.getAge().equals(e2.getAge())) {
//                        return e1.getName().compareTo(e2.getName());
//                    }else {
//                        return e1.getAge().compareTo(e2.getAge());
//                    }
//                }).collect(Collectors.toList()).forEach(System.out::println);
//    }

   
    @Test
    public void test2(){
        List<emp> list = Arrays.asList(
                new emp("xiao",220, emp.Status.BUSY),
                new emp("xia",30, emp.Status.VOCATION),
                new emp("xialijun",99, emp.Status.BUSY),
                new emp("xia0",30, emp.Status.FREE)
        );
        boolean match = list.stream().allMatch((e) -> e.getStatus()
                .equals(emp.Status.BUSY));
        if (StringUtils.isNotBlank(String.valueOf(match))) {
            System.out.println(match);
        }

        System.out.println("===================");
        boolean b = list.stream()
                .anyMatch((e) -> e.getStatus().equals(emp.Status.BUSY));
        System.out.println(b);
        System.out.println("====================");
        Optional<emp> first = list.stream().findFirst();
//        first.orElse(0);
        long count = list.stream().count();
        System.out.println(first);
        System.out.println(count);
        System.out.println("'======================================================");
        Optional<emp> max = list.stream().max(Comparator.comparingInt(emp::getAge));
        System.out.println(max.get());
        System.out.println("-------------------------------------------------------------------------");
        Optional<emp> min = list.stream()
                .filter(e -> e.getStatus().equals(emp.Status.BUSY))
                .min(Comparator.comparingInt(emp::getAge));
        System.out.println(min);

        Optional<Integer> min1 = list.stream().map(emp::getAge).min(Integer::compareTo);
        Optional<Integer> min2 = list.stream().map(emp::getAge).min(Integer::compare);
        System.out.println(min1);
        System.out.println(min2);
    }
}

Stream 流的 约束与收集

**reduce 规约:**可以将流中的元素反复结合起来,得到一个值

reduce 的使用:

 @Test
    public void test3(){
//        Logger logger = new Logger(Test02.class);
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer result = list1.stream().reduce(0, (x, y) -> x + y);
        System.out.println(result);
        System.out.println("==================================");
        Optional<Integer> reduce = list.stream()
                .map(emp::getAge)
                .reduce(Integer::sum);
        System.out.println(reduce);

    }

收集:collect ===> 将流收集起来转成其他形势,.collect(Collectors.toList());

//List集合
    List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer result = list1.stream().reduce(0, (x, y) -> x + y);
        System.out.println(result);
        System.out.println("==================================");
        List<Integer> collect = list.stream()
                .map(emp::getAge)
                .collect(Collectors.toList());
        collect.forEach(System.out::println);
//        System.out.println(reduce);
        list.stream().map(emp::getName).collect(Collectors.toSet()).forEach(System.out::println);
        System.out.println("==========================lklm");
//迭代器
        HashSet<Integer> collect1 = list.stream().map(emp::getAge).collect(Collectors.toCollection(HashSet::new));
        Iterator<Integer> iterator = collect1.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            System.out.println("======" +  next);
        }

        System.out.println("===============================");
//增强for 循环
        for (Integer next : collect1) {
            System.out.println(next);
        }
        System.out.println("===============================");
//foreach 遍历
        collect1.forEach(System.out::println);
    }

 Map<emp.Status, List<emp>> map = list.stream().collect(Collectors.groupingBy(emp::getStatus));
        /**
         * map的遍历方法
         */
        //1 :迭代器
        Iterator<Map.Entry<emp.Status, List<emp>>> iterator1 = map.entrySet().iterator();
        while (iterator1.hasNext()) {
            Map.Entry<emp.Status, List<emp>> nextMap = iterator1.next();
            //emp.Status key = nextMap.getKey();
            System.out.println(nextMap);
        }
        System.out.println("???????????????????????????????????????????????????????????");
        //for 循环
        for (Map.Entry< emp.Status, List<emp>> entry : map.entrySet() ) {
            emp.Status key = entry.getKey();
            List<emp> value = entry.getValue();
            System.out.println(key+":"+value);
        }
    }

时间:

Instant start = Instant.now();

Instant end = Instant.now();

System.out.println("一共花费了:" + Duration.between(start,end).getUnits());

Optional类:

避免空指针异常:

/**
     * OPtional容器类的常用方法:
     *           Optional.of(T, t) :创建一个Optional 类的实例
     *           Optional.empty()  :创建一个空的Optional类的实例
     *           Optional.ofNullable(T ,t) :若t不为空 , 则创建Optional实例 ,否则则创建空实例
     *
     *           isPresent()  : 判断是否包含值
     *           orElse(T t)  : 如果调用对象 包含值 ,则返回该值,否则返回  t
     *           orElseGet (Suppliser s)  :如果 如果调用对象 包含值 ,则返回该值,否则返回 s 获取的值
     *           map (Function  f) 如果有值对其进行处理,并返回先处理后的Optional  ,否则返回 Optional.empty()
     *           flapMap(Function mapper ) :与map相似 , 要求返回值必须是Optional
     */

接口中的默认方法和静态方法:

默认方法:default

类优先的原则:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IFbDSIu0-1665058647033)(C:\Users\12926\AppData\Roaming\Typora\typora-user-images\1658625445426.png)]

时间日期API

datetimeFormatter.ofpattern()

 @Test
    public void test1() {
        // LocalDate   LocalTime   LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        int year = now.getYear();
        System.out.println(year);
        System.out.println("================");
        LocalDateTime of = LocalDateTime.of(2022, 10, 8, 13, 33, 44);
        System.out.println(of);
        LocalDateTime localDateTime = of.plusYears(2);
        System.out.println(localDateTime);
    }
}

时间戳:(Unix 元年 :1970年1月1日 00:00 :00 到现在某个时间段之前的毫秒值)

Instant

@Test
    public void test2() {
        Instant now = Instant.now();
        System.out.println(now);
        System.out.println("=================");
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);
    }
    @Test
    public void test3() throws InterruptedException {
        LocalDate now = LocalDate.now();
        Thread.sleep(1000000000L);
        LocalDate now1 = LocalDate.now();
        Period between = Period.between(now, now1);
        System.out.println(between.getDays());
    }

时间矫正器: TemporalAdjuster

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-c2V1Kab7-1665058647034)(C:\Users\12926\AppData\Roaming\Typora\typora-user-images\1658629734818.png)]

DateTimeFotmatter :格式化时间日期

 @Test
    public void test5() {
        DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");

        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        System.out.println(format);
    }
}

重复注解,类型注解

));
}


### 时间矫正器: TemporalAdjuster

[外链图片转存中...(img-c2V1Kab7-1665058647034)]

DateTimeFotmatter   :格式化时间日期

```java
 @Test
    public void test5() {
        DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");

        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        System.out.println(format);
    }
}

重复注解,类型注解

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/121415.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!