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

Java8新特性

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

Java8新特性

1.概述
1.1为什么学?
  ●能够看懂公司里的代码
  ●大数量下处理集合效率高 (并行流)
  ●代码可读性高
  ●消灭嵌套地狱
 

  例如:

  java8之前代码:

    //查询未成年作家的评分在70以上的书籍由于洋流影响所以作家和书籍可能出现重复,需要进行去重
    List bookList = new ArrayList<>();
    Set uniqueBookValues = new Hashset<>();
    Set uniqueAuthorValues = new HashSet<>();
    for(Author author :authors)
    {
        if (uniqueAuthorValues.add(author)) {
            if (author.getAge() < 18) {
                List books = author.getBooks();
                for (Book book : books) {
                    if (book.getScore() > 70) {
                        if (uniqueBookValues.add(book)) {
                            bookList.add(book);
                        }
                    }
                }
            }
        }
    }
    System.out.println(bookList);

使用函数式编程:

1.2函数式编程思想
  1.2.1概念
           面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。
  1.2.2优点
  ●代码简洁,开发快速
  ●接近自然语言,易于理解
  ●易于"并发编程"

2. Lambda表达式
2.1概述
      Lambda是DK8中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。

2.2核心原则
    可推导可省略
2.3基本格式
   (参数列表)->{代码}

例一
我们在创建线程并启动时可以使用匿名内部类的写法:

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        }).start();
    }

Lambda表示为:

new Thread(() -> System.out.println("hello world")).start();

  这个匿名内部类必须是一个接口且必须只有一个抽象方法 

@FunctionalInterface
public interface Runnable {
    
    public abstract void run();
}

  Lambda表达式不关注类名(接口),也不关注方法名,只关注方法参数和方法体

  刚开始写Lambda表达式可以直接省略到类名和方法名 ,加一个  -> 就可以了

  例如Runnable

    public static void main(String[] args) {
        new Thread(
            ()  -> {
            System.out.println("hello world");
           
        }).start();
    }

根据Lamdba省略规则,进一步省略大括号,小括号等

Lambda表达式省略的都是JDK能识别出来的内容,省略的都是一些没有意义的代码

在Java8支持Lambda表达式以后,为了满足Lambda表达式的一些典型使用场景,JDK为我们提供了大量常用的函数式接口。它们主要在 java.util.function 包中

四大常用函数式接口:

例2: idea自动生成Lambda表达式快捷键 ctrl + 回车 也可以从lambda表达式变成普通写法

    public static void main(String[] args) {
        int i = calculateNum((left, right) -> left + right);
        System.out.println(i);

    }


    public static int calculateNum(IntBinaryOperator operator){

        int a = 10;
        int b = 20;

        return operator.applyAsInt(a,b);

    }

例 3:

    public static void main(String[] args) {
        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value%2==0;
            }
        });

        printNum((int value) -> 
                 value%2==0
        );
    }

    public static void printNum(IntPredicate predicate){

        int[] arr = {1,2,3,4,5,6,7,8,9,10};

        for (int i : arr) {

            if (predicate.test(i)){
                System.out.println(i);
            }
        }
    }

例4:

    public static void main(String[] args) {
        Integer integer = typeConver(s -> Integer.valueOf(s));
        System.out.println(integer+1);

        String s = typeConver((String s)-> {
                return "l" + s;
        });
        System.out.println(s);

    }
    
    public static  R typeConver(Function function){
        String str = "12345";
        R result = function.apply(str);
        return result;
    }

例5 :

    public static void main(String[] args) {
        foreachArr(value -> System.out.println(value));
    }
    
    public static void foreachArr(IntConsumer consumer){
        
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            consumer.accept(i);
        }
        
    }

2.4省略规则
●参数类型可以省略
●方法体只有-句代码时大括号return和唯一 一句代码的分号可以省略
●方法只有一个参数时小括号可以省略
●以上这些规则都记不住也可以省略不记

3. Stream流
3.1概述
Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。

3.2案例数据准备
 

package Stream;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode//用于后期的去重使用
public class Author {
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List books;

}
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode //用于后期的去重使用
public class Book {

    // id
    private Long id;
    // 书名
    private String name;
    // 分类
    private String category;
    // 评分
    private Integer score;
    // 简介
    private String intro;
}

        //数据初始化

        Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
        Author author2 = new Author(2L,"亚拉索",15,"狂风也追逐不上他的思考速度",null);
        Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
        Author author4= new Author(3L,"易",14,"是这个世界在限制他的思维",null);


        //书籍列表
        List book1 = new ArrayList<>();
        List book2 = new ArrayList<>();
        List book3 = new ArrayList<>();


        book1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
        book1.add(new Book(2L,"一个人不能死在同-一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));


        book2.add(new Book(3L,"那风吹不到的地方","哲学" ,85,"带你用思维去领略世界的尽头"));
        book2.add(new Book(3L,"那风吹不到的地方","哲学" ,85,"带你用思维去领略世界的尽头"));
        book2.add(new Book(4L,"吹或不吹","爱情,个人传记" ,56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));



        book3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
        book3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
        book3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

        author.setBooks(book1);
        author2.setBooks(book2);
        author3.setBooks(book3);
        author4.setBooks(book3);

        List authorList = new ArrayList<>(Arrays.asList(author, author2, author3, author4));
        return authorList;

3.3快速入门
3.3.1需求
我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于1 8的作家的名字,并且要注意去重。

    public static void main(String[] args) {
        List authors = getAuthors();
        authors.stream()
                .distinct()
                .filter( author ->
                         author.getAge() < 18
                )
                .forEach(author -> System.out.println(author.getName()));
    }

3.4常用操作
3.4.1创建流
单列集合:1集合对 象.stream()

        List authors = getAuthors();
        Stream stream = authors.stream();

数组:  Arrays .stream(数组)或者使用Stream. of来创建

        Integer[] arr = {1,2,3,4,5};
        Stream stream = Arrays.stream(arr);
        stream.forEach(integer -> System.out.println(integer));
//或
        //Stream stream = Arrays.stream(arr);
        Stream arr1 = Stream.of(arr);
        arr1.forEach(integer -> System.out.println(integer));

双列集合:转换成单列集合后再创建

    private static void test03() {
        Map map = new HashMap<>();
        map.put("蜡笔小新",19);
        map.put("黑子",17);
        map.put("日向",16);
        Set> entries = map.entrySet();
        Stream> stream = entries.stream();

        stream.filter(stringIntegerEntry -> stringIntegerEntry.getValue() > 16)
                .forEach(stringIntegerEntry -> System.out.println(stringIntegerEntry.getKey() + stringIntegerEntry.getValue()));
    }

idea debug查看 

 3.4.2中间操作
  filter
  可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

    private static void test04() {
        List authors = getAuthors();
        //打印所有姓名长度大于1的作家的姓名
        authors.stream().filter(author -> author.getName().length() > 1)
                .forEach( author -> System.out.println(author));
    }

map 转化类型或者计算

        List authors = getAuthors();
        authors.stream()
                .map(author -> author.getAge())  //获取所有作家的年龄 类型转换
                .map(integer ->  integer + 10)    //对整数类型的年龄 加+10
                .forEach(o -> System.out.println(o));  //输出

distinct

可以去除流中的重复的元素

注意: distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。
 

        //打印所有作家的姓名,并且要求其中不能有重复元素。
        List authors = getAuthors();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

sorted
可以对流中的元索进行排序。

例如:
对流中的元素按照年龄进行降序排序,组要求不能有重复的元素。

空参:

        List authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted()
                .forEach(author -> System.out.println(author.getAge()));
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Author implements Comparable {
    //id
    private Long id;
    //姓名
    private String name;



    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List books;

    @Override
    public int compareTo(Author o) {
        return this.getAge() - o.getAge();
    }


 
}

 有参:

        List authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge())
                .forEach(author -> System.out.println(author.getAge()));


注意:如果调用空参的sorted()方法,要流中的元素是实现了Comparable。

limit
可以设置流的最大长度,超出的部分将被抛弃。

例如:
对流中的元素按照年龄进行降序排序,组要求不能有重复的元素然后打印其中年龄最大的两个作家的姓名。
 

        List authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .limit(2)
                .forEach(author -> System.out.println(author.getAge()));

skip
跳过流中的前n个元素,返回剩下的元素

例如:
打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
 

        List authors = getAuthors();
        authors.stream()
                .sorted((o1,o2) -> o2.getAge() - o1.getAge())
                .distinct()
                .skip(1)
                .forEach(author -> System.out.println(author.getAge()));

flatMap
map只能把一个对象转换成另一 个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。 (简单来说,就是author 对应多个 Book,需要把book拼接成一个流,然后去重、输出)


例一:
打印所有书籍的名字。要求对重复的元索进行去重。
 

        List authors = getAuthors();

        authors.stream().flatMap((Function>) author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));

例二:

打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情
 

        List authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .flatMap((Function>) book -> Arrays.stream(book.getCategory().split(",")))
                .filter(b -> !b.contains("爱情")&&!b.contains("小说"))
                .distinct()
                .forEach(c -> System.out.println(c));

3.4.3终结操作
forEach
  对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。

例子:
       输出所有作家的名字

        List authors = getAuthors();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

count
可以用来获取当前流中元素的个数。
例子:
打印这些作家的所出书籍的数目,注意删除重复元素。
 

        List authors = getAuthors();

        long count = authors.stream().flatMap((Function>) author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);

max&min I
可以用来或者流中的最值。
例子:
分别获取这些作家的所出书籍的最高分和最低分并打印。

  max最高分:

        List authors = getAuthors();
        Optional max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .max((score1, score2) -> score1.getScore() - score2.getScore());
        System.out.println(max.get().getScore());

min最低分:

        Optional min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .min((score1, score2) -> score1.getScore() - score2.getScore());
        System.out.println(min.get().getScore());

collect
把当前流转换成一个集合。

例子:
       获取一个存放所有作者名字的List集合。

        List authors = getAuthors();
        List collect = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toList());
        System.out.println(collect);

     获取一个所有作者名的Set集合。
 

        List authors = getAuthors();
        Set collect = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toSet());


        Iterator iterator = collect.iterator();
        while (iterator.hasNext())
        {
            System.out.println(iterator.next());
        }

获取一-个Map集合,map的key为作者名,value,为List

        List authors = getAuthors();
        Map> collect = authors.stream().distinct().collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
        

查找与匹配
   anyMatch
   可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
例子:
判断是否有年龄在29以上的作家 (只要有一个就返回true)

        List authors = getAuthors();

        boolean b = authors.stream()
                .anyMatch(author -> author.getAge() > 29);
        System.out.println(b);

allMatch
可以用来判断是否都符合匹配条件,结果为boolean类型。 如果都符合结果为true,否则结果为false.
例子:
判断是否所有的作家都是成年人(必须所有都满足才返回 true)
 

        List authors = getAuthors();
        boolean b = authors.stream()
                .allMatch(author -> author.getAge() > 29);
        System.out.println(b);

noneMatch
可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false
例子:
判断作家是否都没有超过100岁的。

findAny
获取流中的任意- -个元素。该方法没有办法保证获取的一定是流中的第一个元素。
例子:
获取任意一个年龄大于18的作家,如果存在就输出他的名字
 

        List authors = getAuthors();
        Optional any = authors.stream().filter(author -> author.getAge() > 18).findAny();
        any.ifPresent(author -> System.out.println(author.getName()));

findFirst
获取流中的第一个元素。
例子:
       获取一个年龄最小的作家,并输出他的姓名。
 

        List authors = getAuthors();
        Optional first = authors.stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .findFirst();
        first.ifPresent(author -> System.out.println(author.getName()));

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/844869.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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