java函数式编程stream流操作lambda表达式使用方法引用用法等练习
@Test void test01() { System.out.println("111"); List<Author> authors = getAuthor(); //stream流打对象中一个字段 authors.stream().distinct().forEach(author -> System.out.println(author.name)); //flatMap把一个stream流转成另一个stream流,然后通过map转成对象,最终在转成list //把书名放到一个list中 List<String> name_list = authors.stream().flatMap(author -> author.books.stream()).map(books -> books.name).collect(Collectors.toList()); System.out.println(name_list); } @Test public void test02(){ List<Author> authors = getAuthor(); //引用类的实例方法 System.out::print //打印出所有书名 authors.stream().flatMap(author -> author.books.stream()).map(books -> books.name).forEach(System.out::print); } public static List<Author> getAuthor(){ List<Books> books1 = new ArrayList<Books>() { { add(new Books(1,"书1","小说,科学",10,"简介一11")); add(new Books(2,"书2","计算机,理财",20,"简介一20")); add(new Books(3,"书3","屋里,科学",30,"简介一30")); add(new Books(4,"书4","化学,经济",40,"简介一40")); add(new Books(5,"书5","小说,科学",50,"简介一50")); } }; List<Books> books2 = new ArrayList<Books>() { { add(new Books(6,"书6","小说,科学",60,"简介一61")); add(new Books(7,"书7","计算机,理财",70,"简介一70")); add(new Books(8,"书8","屋里,科学",80,"简介一80")); } }; List<Books> books3 = new ArrayList<Books>() { { add(new Books(9,"书9","小说,科学",90,"简介一90")); add(new Books(10,"书10","计算机,理财",100,"简介一100")); } }; List<Author> authors = new ArrayList<Author>(){ { add(new Author(1,"作者1",11,books1)); add(new Author(2,"作者2",22,books2)); add(new Author(3,"作者3",33,books3)); } }; return authors; } @Data @AllArgsConstructor @NoArgsConstructor public static class Author { public Integer id; public String name; public Integer age; public List<Books> books; } @Data @AllArgsConstructor @NoArgsConstructor public static class Books { public Integer id; public String name; public String category; public Integer socre; public String intro; }
参: https://www.bilibili.com/video/BV1Gh41187uR
标签:java,stream,List,add,Books,new,public,lambda From: https://www.cnblogs.com/fps2tao/p/17430504.html