詳細參考: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;
/**
* 總數(shù)量
*/
private Integer totalQuantity;
}
List<Books> list = booksMapper.findBooksName(null); // 查詢全部
Stream流對集合的應用
1. 遍歷文章來源:http://www.zghlxwxcb.cn/news/detail-836805.html
List<Books> bookList = // 獲取你的書籍列表
// 使用 Stream API 遍歷列表
bookList.forEach(book -> {
// 在這里不執(zhí)行其他操作,只是遍歷
System.out.println(book); // 或者其他你想要的操作
});
?2. 匯總文章來源地址http://www.zghlxwxcb.cn/news/detail-836805.html
List<Books> bookList = // 獲取你的書籍列表
// 1. 過濾(Filtering):保留總數(shù)量大于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. 計數(shù)(Counting):計算圖書總數(shù)
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. 分區(qū)(Partitioning):將圖書分為數(shù)量大于0和數(shù)量為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) {
// 創(chuàng)建一個包含學生姓名和對應成績的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);
}
}
到了這里,關于Java,SpringBoot中對Stream流的運用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!