详细参考:java 1.8 stream 应用-22种案例_java1.8 流案例-CSDN博客
准备条件
public class Books implements Serializable {private static final long serialVersionUID = 1L;/*** 图书记录ID,自增*/private Integer bookId;/*** 图书号*/private String bookCode;/*** 图书类型*/private String bookType;/*** 图书名称*/private String bookName;/*** 作者名称*/private String authorName;/*** 出版社*/private String publisher;/*** 总数量*/private Integer totalQuantity;
}
List<Books> list = booksMapper.findBooksName(null); // 查询全部
Stream流对集合的应用
1. 遍历
List<Books> bookList = // 获取你的书籍列表// 使用 Stream API 遍历列表
bookList.forEach(book -> {// 在这里不执行其他操作,只是遍历System.out.println(book); // 或者其他你想要的操作
});
2. 汇总
List<Books> bookList = // 获取你的书籍列表// 1. 过滤(Filtering):保留总数量大于0的图书
List<Books> filteredBooks = bookList.stream().filter(book -> book.getTotalQuantity() > 0).collect(Collectors.toList());// 2. 映射(Mapping):提取图书名称形成新的列表
List<String> bookNames = bookList.stream().map(Books::getBookName).collect(Collectors.toList());// 3. 计数(Counting):计算图书总数
long bookCount = bookList.stream().count();// 4. 查找(Finding):找到集合中的任意一本图书
Optional<Books> anyBook = bookList.stream().findAny();
Optional<Books> firstBook = bookList.stream().findFirst();// 5. 排序(Sorting):按照图书名称排序
List<Books> sortedBooks = bookList.stream().sorted(Comparator.comparing(Books::getBookName)).collect(Collectors.toList());// 6. 分组(Grouping):按照图书类型分组
Map<String, List<Books>> booksByType = bookList.stream().collect(Collectors.groupingBy(Books::getBookType));// 7. 分区(Partitioning):将图书分为数量大于0和数量为0的两部分
Map<Boolean, List<Books>> partitionedBooks = bookList.stream().collect(Collectors.partitioningBy(book -> book.getTotalQuantity() > 8));
Map集合运用Stream流
import java.util.HashMap;
import java.util.Map;public class StreamExample {public static void main(String[] args) {// 创建一个包含学生姓名和对应成绩的Map集合Map<String, Integer> studentScores = new HashMap<>();studentScores.put("Alice", 85);studentScores.put("Bob", 92);studentScores.put("Charlie", 78);studentScores.put("David", 95);studentScores.put("Eva", 88);// 使用Stream流处理Map集合studentScores.entrySet().stream()// 过滤出成绩大于等于90的学生.filter(entry -> entry.getValue() >= 90)// 获取学生姓名并打印.map(Map.Entry::getKey).forEach(System.out::println);}
}