数据准备
```java public class Author { private Long id; private String name; private Integer age; private String intro; private List books; }
public class Book { private Long id; private String name; private String category; // "哲学,爱情,个人成长,个人传记" private Integer score; private String intro; } ```
```java private static List getAuthors() { //数据初始化 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<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();
books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));
books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);
List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
return authorList;
}
```
创建流
单列集合:
集合对象.stream()
数组:
Arrays.stream(数组)
双列集合:转换成单列集合后再创建
```java Map map = new HashMap<>(); map.put("张三",17); map.put("向阳",16);
Stream > stream = map.entrySet().stream(); ```
中间操作
map
java // 打印所有作家名字 List<Author> authors = getAuthors(); authors.stream().map(s -> s.getName()).forEach(s -> System.out.println(s));
sort()
java // 对年龄进行降序, 版本一 List<Author> authors = getAuthors(); authors.stream() .sorted() // 空参的sorted()方法,需要流中的元素是实现了Comparable .forEach(author -> System.out.println(author.getAge()));
java // 对年龄进行降序, 版本二 authors.stream() .sorted((o1, o2) -> o2.getAge()-o1.getAge()) .forEach(author -> System.out.println(author.getAge()));
flatMap
java // 打印出书的类别 List<Author> authors = getAuthors(); authors.stream() .flatMap(author -> author.getBooks().stream()) .distinct() .flatMap(book -> Arrays.stream(book.getCategory().split(","))) .distinct() .forEach(category-> System.out.println(category));
终结操作
forEach
count
java // 打印所有作家的书籍数量 long count = authors.stream() .flatMap(s -> s.getBooks().stream()) .distinct() .count(); System.out.println(count);
max、min
java Optional<Book> maxScoreBook = authors.stream() .flatMap(s -> s.getBooks().stream()) .max((book1, book2) -> book1.getScore() - book2.getScore());
collect
获取Map集合,map中key为作者名,value为List<Book>
```java // 简洁版 Map > authorList = authors.stream() .distinct() .collect(Collectors.toMap(Author::getName, Author::getBooks));
// 详细版 Map > list = authors.stream() .distinct() .collect(Collectors.toMap( new Function () { @Override public String apply(Author author) { return author.getName(); } }, new Function >() { @Override public List apply(Author author) { return author.getBooks(); } } )); ```
anyMatch
是否有一个符合条件的元素,有一个满足则为true,否则为false
java // 判断是否有年龄在29以上的作家 List<Author> authors = getAuthors(); boolean flag = authors.stream()
allMatch
所有元素是否都符合指定条件,都符合为true,否则为false
java // 判断是否所有的作家都是成年人 List<Author> authors = getAuthors(); boolean flag = authors.stream() .allMatch(author -> author.getAge() >= 18); System.out.println(flag);
noneMatch
所有元素是否都不符合指定条件,都不符合结果为true,否则为false
java // 判断作家是否都没有超过100岁的。 List<Author> authors = getAuthors(); boolean flag = authors.stream() .noneMatch(author -> author.getAge() > 100);
findFirst
java // 获取年龄最小的作家,并输出他的名字 List<Author> authors = getAuthors(); Optional<Author> first = authors.stream() .sorted((o1, o2) -> o1.getAge() - o2.getAge()) .findFirst(); first.ifPresent(author -> System.out.println(author.getName()));
reduce
将流中的元素按指定规则计算出一个结果,一个参数的内部计算过程(还有两个参数、三个参数的重载方法):
java boolean foundAny = false; T result = null; // result返回结果 for (T element : this stream) { if (!foundAny) { foundAny = true; result = element; // 将第一个元素赋值给result,进行初始化 } else result = accumulator.apply(result, element); // 自己定义的计算规则 } return foundAny ? Optional.of(result) : Optional.empty();
example:求所有作家中年龄的最大值
java Optional<Integer> res = authors.stream() .map(Author::getAge) // (result, element)整体作为一个参数 .reduce((result, element) -> element > result ? element : result); // result:返回结果,element:流中的每个元素,初始化时流中第一个元素赋值给result,后面元素按照指定规则计算后赋值给result