如何使用Java Streams根据指定书籍获取作者列表
Java Streams 根据书籍名称获取作者列表
我需要用Java Streams实现根据指定书籍名称获取对应的作者列表。目前只能拿到书籍对象,但Book类没有和Author建立关联,没法直接从Book反向找作者。只接受Java Streams的解决方案,感谢帮忙。
我之前试了下面的代码,但它只会收集匹配的书籍名称,不是我要的作者列表:
authors.stream() .forEach( author -> { author.getBooks().stream() .filter(book -> book.getName().contains(bookName)) .forEach(book -> authorNames.add(book.getName())); });
相关实体类及测试代码如下:
public class Author { String name; List<Book> books; public String getName() { return name; } public List<Book> getBooks() { return books; } } public class Book { String name; public String getName() { return name; } } public class Library { List<Author> authors; public List<Author> getAuthors() { return authors; } public List<String> search(String bookName) { List<String> authorNames = new ArrayList<>(); // 待实现代码 return authorNames; } } public class Test { public static void main(String[] args) { Author auth1 = new Author( "James D.", List.of( new Book("Forest Run"), new Book("On The Moon"), new Book("Rising Sun"), new Book("Afternoon Sun"))); Author auth2 = new Author( "Martha S.", List.of( new Book("Run Away"), new Book("Are We Moving"), new Book("Sun Is Shining"), new Book("New Moon"))); Author auth3 = new Author( "Phillip R.", List.of( new Book("On The Rock"), new Book("Darkness Of Moon"), new Book("A Walk In The Park"), new Book("Rising Tide"))); Library lib = new Library(List.of(auth1, auth2, auth3)); System.out.println(lib.search("Run")); } }
正确的Streams实现
核心逻辑:遍历所有作者,筛选出拥有包含指定名称书籍的作者,提取这些作者的名称并收集为列表,无需手动维护集合。
修改后的Library.search方法代码:
import java.util.stream.Collectors; public List<String> search(String bookName) { return getAuthors().stream() // 过滤出拥有匹配书籍的作者,anyMatch做短路判断提升效率 .filter(author -> author.getBooks().stream() .anyMatch(book -> book.getName().contains(bookName))) // 将Author对象映射为作者名称字符串 .map(Author::getName) // 收集为最终列表 .collect(Collectors.toList()); }
代码说明
filter阶段:对每个作者,检查其书籍列表中是否存在名称包含目标字符串的书籍,anyMatch会在找到第一个匹配项后停止遍历该作者的书籍,避免不必要的计算。map阶段:将符合条件的Author对象转换为对应的名称字符串。collect阶段:将流式处理的结果收集为List返回。
测试结果
运行Test类的main方法,输入"Run"时,输出结果为:
[James D., Martha S.]
符合预期——James D.的《Forest Run》、Martha S.的《Run Away》均包含"Run"关键字。
内容的提问来源于stack exchange,提问作者PramTal
相关产品推荐
相关产品推荐

