答案:通过定义Book类和BookSearch管理类,使用ArrayList存储图书并利用Stream API实现按书名、作者、ISBN的模糊搜索及组合条件查询。示例展示了添加图书和多种搜索功能,适用于小型应用或学习场景。

在Java中实现图书搜索功能,核心是定义图书数据结构、存储图书信息,并提供按条件查询的方法。可以使用简单的集合类存储数据,结合面向对象设计,实现灵活的搜索逻辑。以下是具体实现思路和代码示例。
创建一个Book类,包含常见属性如书名、作者、ISBN、出版年份等,并重写toString()方法方便输出。
public class Book {
private String title;
private String author;
private String isbn;
private int publicationYear;
public Book(String title, String author, String isbn, int publicationYear) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.publicationYear = publicationYear;
}
// Getter 方法
public String getTitle() { return title; }
public String getAuthor() { return author; }
public String getIsbn() { return isbn; }
public int getPublicationYear() { return publicationYear; }
<strong>@Override</strong>
public String toString() {
return "《" + title + "》 by " + author + " (ISBN: " + isbn + ", " + publicationYear + ")";
}
}使用ArrayList存储图书对象,提供添加图书和多种搜索方法。
import java.util.*;
public class BookSearch {
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
}支持按书名、作者或ISBN进行模糊搜索:
立即学习“Java免费学习笔记(深入)”;
public List<Book> searchByTitle(String keyword) {
return books.stream()
.filter(book -> book.getTitle().toLowerCase().contains(keyword.toLowerCase()))
.toList();
}
public List<Book> searchByAuthor(String keyword) {
return books.stream()
.filter(book -> book.getAuthor().toLowerCase().contains(keyword.toLowerCase()))
.toList();
}
public List<Book> searchByIsbn(String keyword) {
return books.stream()
.filter(book -> book.getIsbn().contains(keyword))
.toList();
}如果需要同时匹配多个条件,可以扩展搜索方法:
public List<Book> searchBooks(String titleKeyword, String authorKeyword) {
return books.stream()
.filter(book ->
(titleKeyword == null || book.getTitle().toLowerCase().contains(titleKeyword.toLowerCase())) &&
(authorKeyword == null || book.getAuthor().toLowerCase().contains(authorKeyword.toLowerCase()))
)
.toList();
}调用示例:
public class Main {
public static void main(String[] args) {
BookSearch searcher = new BookSearch();
searcher.addBook(new Book("Java编程思想", "Bruce Eckel", "978-0131872486", 2007));
searcher.addBook(new Book("Effective Java", "Joshua Bloch", "978-0134685991", 2018));
searcher.addBook(new Book("深入理解Java虚拟机", "周志明", "978-7111421187", 2013));
System.out.println("搜索书名包含 'Java' 的图书:");
searcher.searchByTitle("Java").forEach(System.out::println);
System.out.println("\n搜索作者为 '周志明' 的图书:");
searcher.searchByAuthor("周志明").forEach(System.out::println);
}
}基本上就这些。这个实现适合小型应用或学习用途。如果数据量大或需要高性能搜索,可考虑引入数据库(如SQLite)或搜索引擎(如Lucene)。但纯Java环境下,利用集合和Stream API已能快速构建实用的图书搜索功能。
以上就是如何在Java中实现图书搜索功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号