本文介绍: 【代码】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());

原文地址:https://blog.csdn.net/jl15988/article/details/134716498

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_17737.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注