Stream流的各种API方法(补充) -- 通过实体操作

1. 创建Author 作家实体

import java.util.List;

/**
 * 作家
 */
public class Author {
    private Integer id;
    private String name;
    private Integer age;
    private String intro;  // 简介
    private List<Book> books;   // 作品

    public Author(Integer id, String name, Integer age, String intro, List<Book> books) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.intro = intro;
        this.books = books;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getIntro() {
        return intro;
    }

    public void setIntro(String intro) {
        this.intro = intro;
    }

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    @Override
    public String toString() {
        return "Author{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", intro='" + intro + '\'' +
                ", books=" + books +
                '}';
    }
}

2. 创建 Book 作品实体

/**
 * 作品
 */
public class Book {
    private Integer id;
    private String name;
    private String category; // 分类
    private Integer score; // 评分
    private String intro;  // 简介

    public Book(Integer id, String name, String category, Integer score, String intro) {
        this.id = id;
        this.name = name;
        this.category = category;
        this.score = score;
        this.intro = intro;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public String getIntro() {
        return intro;
    }

    public void setIntro(String intro) {
        this.intro = intro;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", category='" + category + '\'' +
                ", score=" + score +
                ", intro='" + intro + '\'' +
                '}';
    }
}

3. 通过 stream 流的API操作实体数据

import java.util.*;
import java.util.stream.Collectors;

public class Demo7 {

    public static void main(String[] args) {
        List<Author> authors = getAuthor();
        // 打印年龄大于29岁的作家,并且需要去重  按ID去重
        authors.stream().filter(s -> s.getAge() > 29)
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        s -> s.getId()  // 根据作者ID去重
                                )
                        )),ArrayList::new
                )).forEach(s -> System.out.println(s));

        System.out.println("================== 1 ======================");

        // 打印年龄大于29岁的作家,并且需要去重  按作者名字和年龄去重
        authors.stream().filter(s -> s.getAge() > 29)
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        s -> s.getName() + ";" + s.getAge()  // 根据作者名字和年龄去重
                                )
                        )),ArrayList::new
                )).forEach(s -> System.out.println(s));

        System.out.println("================== 2 ======================");

        // 打印姓名长度大于2的作家姓名
        authors.stream().filter(s -> s.getName().length() > 2)
                .forEach(s -> System.out.println(s.getName()));

        System.out.println("================== 3 ======================");

        // 使用map打印所有的作家姓名
        authors.stream().map(author -> author.getName()).forEach(name -> System.out.println(name));

        System.out.println("================== 4 ======================");

        // 对流中的元素按照年龄进行降序排列  如果调用空参的sorted()方法, 流中的实体元素需要实现Comparable接口
        authors.stream().sorted((Author o1, Author o2) -> o2.getAge() - o1.getAge())
                .forEach(author -> System.out.println(author.getName() + ":" + author.getAge()));

        System.out.println("================== 5 ======================");

        // 打印所有的书籍名称,并且去重
        authors.stream().flatMap(author -> author.getBooks().stream())
                .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(
                                book -> book.getId()
                        )
                )),ArrayList::new
        )).forEach(book -> System.out.println(book.getName()));

        System.out.println("================== 6 ======================");

        // 打印所有的书籍的分类,并且去重   注意: 玄幻,爱情  应该转换成两种分类   flatMap()
        authors.stream().flatMap(author -> author.getBooks().stream())
                .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(
                                book -> book.getId()  // 对书籍去重
                        )
                )),ArrayList::new
            )).stream().flatMap(book -> Arrays.stream(book.getCategory().split(",")))
                .distinct()  // 对分类去重
                .forEach(category -> System.out.println(category));

        System.out.println("================== 7 ======================");

        // 打印总书籍数量, 注意去重    count()
        long count = authors.stream().flatMap(author -> author.getBooks().stream())
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(book -> book.getId())
                        )), ArrayList::new
                )).stream().count();
        System.out.println(count);

        System.out.println("================== 8 ======================");

        // 获取书籍的最高评分和最低评分   max()  min()
        Integer maxScore = authors.stream().flatMap(author -> author.getBooks().stream())
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(book -> book.getId())
                        )), ArrayList::new
                )).stream()
                .max((Book book1, Book book2) -> book1.getScore() - book2.getScore())
                .get()
                .getScore();
        System.out.println("最高分:" + maxScore);

        Integer minScore = authors.stream().flatMap(author -> author.getBooks().stream())
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(book -> book.getId())
                        )), ArrayList::new
                )).stream()
                .min((Book book1, Book book2) -> book1.getScore() - book2.getScore())
                .get()
                .getScore();
        System.out.println("最低分:" + minScore);

        System.out.println("================== 9 ======================");

        // 获取一个存放所有作者名字的list集合   collect(Collectors.toList())
        List<String> nameList = authors.stream().map(author -> author.getName())
                .distinct()
                .collect(Collectors.toList());
        System.out.println(nameList);

        // 获取一个所有书名的set集合   collect(Collectors.toSet())
        Set<String> nameSet = authors.stream().flatMap(author -> author.getBooks().stream())
                .map(book -> book.getName())
                .distinct()
                .collect(Collectors.toSet());
        System.out.println(nameSet);

        // 获取一个map集合, key为作者名,value为对应的作品  注意: key值唯一   collect(Collectors.toMap(key,value))
        Map<String, List<Book>> map = authors.stream()
                .collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(author -> author.getName() + "," + author.getAge())  // 先去重
                    )),ArrayList::new
                )).stream()
                .collect(Collectors.toMap(
                author -> author.getName(), author -> author.getBooks()
        ));
        System.out.println(map);

        System.out.println("================== 10 ======================");

        // 判断是否有年龄在30岁以上的作家     anyMatch()
        boolean ageFlag = authors.stream().anyMatch(author -> author.getAge() > 30);
        System.out.println(ageFlag);

        // 判断所有的作家是否都是成年人       allMatch()
        boolean allFlag = authors.stream().allMatch(author -> author.getAge() >= 18);
        System.out.println(allFlag);

        // 判断所有的作家是否都不超过40岁     noneMatch()
        boolean noneFlag = authors.stream().noneMatch(author -> author.getAge() > 40);
        System.out.println(noneFlag);

        System.out.println("================== 11 ======================");

        // 获取任意一个大于18岁的作家,如果存在则输出名字     findAny()   注意: 需要判断是否获取到数据     ifPresent()
        Optional<Author> optional = authors.stream().filter(author -> author.getAge() > 18).findAny();
        optional.ifPresent(author -> System.out.println(author.getName()));

        // 获取年龄最大的作家, 并输出他的名字   findFirst()  获取第一个元素
        Optional<Author> firstOptional = authors.stream()
                .sorted((Author author1, Author author2) -> author2.getAge() - author1.getAge())
                .findFirst();
        firstOptional.ifPresent(author -> System.out.println(author.getName()));

        System.out.println("================== 11 ======================");

        // 求所有作者的年龄之和   reduce(参数一,计算方式)   参数一: 传入值
        // 计算方式(参数1,参数2): 按某种计算方式返回结果.  参数1: reduce的参数一,即传入值  参数2: stream流中的数据
        Integer sum = authors.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(author -> author.getId())
                )), ArrayList::new
        )).stream()
          .map(author -> author.getAge())
          .reduce(0, (result, age) -> result + age);
        System.out.println("年龄之和:" + sum);

        // 使用reduce获取最大年龄   Integer.MIN_VALUE: Integer的最小值
        Integer maxAge = authors.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(author -> author.getId())
                )), ArrayList::new
        )).stream()
            .map(author -> author.getAge())
            .reduce(Integer.MIN_VALUE, (result, age) -> result<age?age:result);
        System.out.println("最大年龄:" + maxAge);

        // 使用reduce获取最小年龄   Integer.MAX_VALUE: Integer的最大值
        Integer minAge = authors.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(author -> author.getId())
                )), ArrayList::new
        )).stream()
            .map(author -> author.getAge())
            .reduce(Integer.MAX_VALUE, (result, age) -> result<age?result:age);
        System.out.println("最小年龄:" + minAge);

        // 使用reduce获取最小年龄  reduce 不传入初始值
        Optional<Integer> reduce = authors.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(author -> author.getId())
                )), ArrayList::new
        )).stream()
                .map(author -> author.getAge())
                .reduce((result, age) -> result < age ? result : age);
        reduce.ifPresent(age -> System.out.println("最小年龄:" + age));


    }

    /**
     * 作者数据准备
     * @return
     */
    private static List<Author> getAuthor(){
        // 数据初始化
        Author author1 = new Author(1,"天蚕土豆",29,"白金作家,玄幻小说巅峰作家",null);
        Author author2 = new Author(2,"唐家三少",35,"白金作家,斗罗大陆系列引人眼球",null);
        Author author3 = new Author(3,"猫腻",34,"白金作家,武侠类小说牛逼",null);
        Author author4 = new Author(3,"猫腻",34,"白金作家,武侠类小说牛逼",null);

        // 书籍列表
        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        books1.add(new Book(1,"斗破苍穹","玄幻",100,"三十年河东,三十年河西,莫欺少年穷! 年仅15岁的萧家废物,于此地,立下了誓言,从今以后便一步步走向斗气大陆巅峰"));
        books1.add(new Book(2,"武动乾坤","玄幻",98,"大炎王朝天都郡炎城青阳镇,落魄的林氏子弟林动在山洞间偶然捡到一块神秘的石符而走上的逆袭之路"));

        books2.add(new Book(3,"斗罗大陆","玄幻,爱情",100,"穿越到斗罗大陆的唐三如何一步步修炼武魂,由人修炼为神,最终铲除了斗罗大陆上的邪恶力量,报了杀母之仇,成为斗罗大陆最强者"));
        books2.add(new Book(3,"斗罗大陆","玄幻,爱情",100,"穿越到斗罗大陆的唐三如何一步步修炼武魂,由人修炼为神,最终铲除了斗罗大陆上的邪恶力量,报了杀母之仇,成为斗罗大陆最强者"));
        books2.add(new Book(4,"神印王座","玄幻,魔法",97,"魔族强势,在人类即将被灭绝之时,六大圣殿崛起,带领着人类守住最后的领土。一名少年,为救母加入骑士圣殿,奇迹、诡计,不断在他身上上演。在这人类六大圣殿与七十二柱魔神相互倾轧的世界,他能否登上象征着骑士最高荣耀的神印王座"));

        books3.add(new Book(5,"择天记","玄幻,哲学,爱情",99,"在人妖魔共存的架空世界里,陈长生为了逆天改命,带着一纸婚书来到神都,与一群少年英雄伙伴并肩与黑暗势力展开了殊死斗争,同时也收获了爱情,在神都开启一个逆天强者的崛起征程"));
        books3.add(new Book(6,"庆余年","历史,哲学",98,"小说讲述了叫范闲的年轻人的成长路程,庆国几十年起伏的画卷慢慢地呈现出来。 几十年的历程里,我们看到的是三代风云人物的起起落落、轮转更替"));
        books3.add(new Book(6,"庆余年","历史,哲学",98,"小说讲述了叫范闲的年轻人的成长路程,庆国几十年起伏的画卷慢慢地呈现出来。 几十年的历程里,我们看到的是三代风云人物的起起落落、轮转更替"));

        author1.setBooks(books1);
        author2.setBooks(books2);
        author3.setBooks(books3);
        author4.setBooks(books3);

        ArrayList<Author> authors = new ArrayList<>(Arrays.asList(author1, author2, author3, author4));
        return authors;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值