Java之Stream的实用语法

1. 转Map

List<Book> books = bookMapper.list();
Map<String, Book> bookMap = books.stream().collect(Collectors.toMap(Book::getBookId, book -> book));

结果结构

{
    "1": {
        "bookId": "1",
        "bookTitle": "书1"
    },
    "2": {
        "bookId": "2",
        "bookTitle": "书2"
    },
}

2. 字符串拼接

List<Book> books = bookMapper.list();
String bookNames = books.stream().map(Book::getBookTitle).collect(Collectors.joining(","));

结果结构

"书1,书2"

3. 类型转换

List<Book> books = bookMapper.list();
List<Book2> book2s = books.stream().map(book -> {
    Book2 book2 = new Book2();
    BeanUtils.copyProperties(book, book2);
}).collect(Collectors.toList());

4. 条件判断(存在任意匹配的)

List<Book> books = bookMapper.list();
if (books.stream().anyMatch(book -> !book.getBookTitle.contains("书"))) {
    throw new RuntimeException("存在非正常书名称");
} else {
    return books;
}

5. 条件判断(无匹配的)

List<Book> books = bookMapper.list();
if (books.stream().noneMatch(book -> "1".equals(book.getType()))) {
    throw new RuntimeException("无指定类型的书籍");
}

6. 修改数据项

List<Book> books = bookMapper.list();
return books.stream().peek(book -> book.setBookTitle(null)).collect(Collectors.toList());

7. 过滤

List<Book> books = bookMapper.list();
return books.stream().filter(book -> "1".equals(book.getType())).collect(Collectors.toList());

8. 排序

List<Book> books = bookMapper.list();
return books.stream().sorted(Comparator.comparing(Book::getCreateTime)).collect(Collectors.toList());

你可能感兴趣的:(Java,java,开发语言,Stream,语法)