@Data
@ToString
public class Book {
private String category;
private String name;
private int stock;
public Book(String category, String name, int stock) {
this.category = category;
this.name = name;
this.stock = stock;
}
}
public static void main(String[] args) {
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("小说", "《西游记》", 1));
bookList.add(new Book("小说", "《鹿鼎记》", 2));
bookList.add(new Book("历史", "《史记》", 3));
bookList.add(new Book("历史", "《四书五经》", 4));
Map<String, List<Book>> bookMap1 = bookList.stream()
.collect(Collectors.groupingBy(Book::getCategory));
Map<String, List<Book>> bookMap5 = bookList.stream()
.collect(Collectors.groupingBy(book -> book.getStock() >= 2 ? "备货充足": "缺货"));
System.out.println(bookMap5);
Map<String, List<String>> bookMap2 = bookList.stream()
.collect(Collectors.groupingBy(Book::getCategory, Collectors.mapping(Book::getName, Collectors.toList())));
Map<String, Integer> bookMap3 = bookList.stream()
.collect(Collectors.toMap(Book::getName, Book::getStock, (oldVal, newVal) -> newVal));
Map<String, Integer> bookMap4 = bookList.stream()
.collect(Collectors.toMap(Book::getCategory, Book::getStock, Integer::sum));
List<List<Integer>> listList = new ArrayList<>();
listList.add(Arrays.asList(1, 2, 3));
listList.add(Arrays.asList(4, 5, 6));
listList.add(Arrays.asList(7, 8, 9));
List<Integer> resultList = listList.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
}