首先定义一下准备工作
package com.chaojilaji.work.statedemo.lambdademo2;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
@Getter
@Setter
public class Book{
private double money;
private String bookName;
private String title;
private List<String> auther;
private String topic;
private int pageCount;
private LocalDate pubDate;
private double height;
public Book(Builder builder){
this.auther = builder.auther;
this.bookName = builder.bookName;
this.height = builder.height;
this.money = builder.money;
this.pageCount = builder.pageCount;
this.pubDate = builder.pubDate;
this.title = builder.title;
this.topic = builder.topic;
}
@Override
public boolean equals(Object object){
if (object instanceof Book){
Book book = (Book) object;
if (book.getAuther()==this.getAuther() && book.getPageCount()==this.getPageCount()){
return true;
}
}
return false;
}
public static class Builder{
private double money;
private String bookName;
private String title;
private List<String> auther;
private String topic;
private int pageCount;
private LocalDate pubDate;
private double height;
public Builder setMoney(double money){
this.money = money;
return this;
}
public Builder setBookName(String bookName){
this.bookName = bookName;
return this;
}
public Builder setAuther(List<String> authers){
this.auther = authers;
return this;
}
public Builder setTitle(String title){
this.title = title;
return this;
}
public Builder setTopic(String topic){
this.topic = topic;
return this;
}
public Builder setPageCount(int pageCount){
this.pageCount = pageCount;
return this;
}
public Builder setPubDate(LocalDate pubDate){
this.pubDate = pubDate;
return this;
}
public Builder setHeight(int height){
this.height = height;
return this;
}
public Book build(){
return new Book(this);
}
}
}
初始化一个Book的列表
private static List<Book> initBooks() {
int n = 100;
List<Book> books = new ArrayList<>();
for (int i = 0; i < n; i++) {
int m = 10;
List<String> s = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
StringBuffer stringBuffer = new StringBuffer();
for (int j = 0; j < m; j++) {
stringBuffer.append(s.get(new Random().nextInt(s.size())));
}
Book book = new Book.Builder()
.setBookName("精通".concat(stringBuffer.toString()))
.setAuther(Arrays.asList("aaa", "bbb", "ccc", "abc"))
.setHeight(20)
.setMoney(new Random().nextDouble() * 100)
.setPageCount(new Random().nextInt(1000))
.setPubDate(LocalDate.now())
.setTitle(stringBuffer.toString())
.setTopic(stringBuffer.substring(0, m - 5 > 0 ? m - 5 : 1)).build();
books.add(book);
}
return books;
}
上面的内容大家可以自由发挥,跟教程无关。下面,进入正题。
获取书的流
List<Book> library = initBooks();
Stream<Book> bookStream = library.parallelStream();
parallelStream()方法获取的是多核并行处理流
获取属性流
List<Book> library = initBooks();
Stream<Book> bookStream = library.parallelStream(); // 获取书的流
Stream<String> titles = bookStream.map(Book::getTitle); // 获取标题流
Stream<Integer> pageCounts = bookStream.map(Book::getPageCount); // 页数流
主流.map(类名::get属性)
根据xxx属性排序
Stream<Book> bookStream1 = library.parallelStream()
.sorted(Comparator.comparing(Book::getBookName));
flatMap
如果属性是List,如何获取属性流,flatMap 不仅是将单个的list属性拿出来,而且还会将多个整理成一个统一的流,即flatMap接受的lambda参数是一个流,功能是 合在一起
Stream<String> authers = library.parallelStream()
.sorted(Comparator.comparing(Book::getBookName))
.flatMap(book -> book.getAuther().parallelStream());
int pageCountSum = library.parallelStream()
.sorted(Comparator.comparing(Book::getBookName))
.flatMapToInt(book -> IntStream.of(book.getPageCount()))
.sum();
去重
Stream<String> authers = library.parallelStream()
.sorted(Comparator.comparing(Book::getBookName))
.flatMap(book -> book.getAuther().parallelStream());
authers = authers.distinct();
截断
包含向前截断和向后截断两种,limit是取前n个,skip是舍去前n个
List<Book> books2 = library.parallelStream()
.sorted(Comparator.comparing(Book::getMoney))
.skip(50)
.collect(Collectors.toList()); // 截断前50,返回剩下的
List<Book> books3 = library.parallelStream()
.sorted(Comparator.comparing(Book::getMoney))
.limit(50)
.collect(Collectors.toList()); // 获取前50
获取最早出版的图书
Optional<Book> optionalBooks = bookStream2.min(Comparator.comparing(Book::getPubDate));
过滤
optionalBooks = optionalBooks.filter(book -> (book.getMoney() - 30.0) < 0.0001);
bookStream2 = bookStream2.filter(book -> (book.getMoney() - 30.0) < 0.0001);
peek的用法 : 一般用于输出中间结果,对调试提供支持
library.parallelStream().peek(book -> log.info("{}", book.getBookName()));
将流转回数据结构
Set<Book> books1 = bookStream2.collect(Collectors.toSet());
Set<String> titleSet = titles.collect(Collectors.toSet());
List<Book> books = bookStream1.collect(Collectors.toList());
搜索操作 anyMatch allMatch noneMatch
boolean res = library.parallelStream()
.mapToInt(Book::getPageCount)
.noneMatch(pageCount -> pageCount > 500);
res = library.parallelStream()
.mapToInt(Book::getPageCount)
.allMatch(pageCount -> pageCount <= 500);
res = library.parallelStream()
.mapToInt(Book::getPageCount)
.anyMatch(pageCount -> pageCount > 500);
findFirst & findAny
Optional<Book> books4 = library.parallelStream()
.findAny();
Optional<Book> book5 = library.parallelStream()
.findFirst();
统计
IntSummaryStatistics intSummaryStatistics = bookStream1.mapToInt(Book::getPageCount)
.summaryStatistics();
结果变成map
library.parallelStream()
.collect(Collectors.groupingBy(Book::getTopic));
library.parallelStream()
.filter(book -> book.getPageCount() < 300)
.collect(Collectors.toMap(Book::getAuther, Book::getBookName));
library.parallelStream()
.filter(book -> book.getPageCount() < 300)
.collect(Collectors.toMap(Book::getBookName, Book::getPubDate, (x, y) -> x.isAfter(y) ? x : y));
Map<String,String> ans123 = library.parallelStream()
.collect(Collectors.toMap(Book::getBookName,Book::getTitle, BinaryOperator.maxBy(naturalOrder()),TreeMap::new));
forEach会终止一个流,但是是并行的
library.parallelStream().forEach(book -> {
log.info("{} {} {} {}", book.getBookName(), book.getAuther(), book.getPubDate(), LocalDateTime.now());
});
forEachOrdered是同步的
library.parallelStream().forEachOrdered(book -> {
log.info("{} {} {} {}", book.getBookName(), book.getAuther(), book.getPubDate(), LocalDateTime.now());
});
来源:CSDN
作者:炒鸡辣鸡复读机
链接:https://blog.csdn.net/xielinrui123/article/details/103242259