java实现图书查看部分,先获取key,根据key遍历所有集合value,遍历每个类目下的集合value的代码
时间: 2023-06-04 19:07:54 浏览: 96
以下是一份示例代码,可以作为参考:
```
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class BookCatalog {
private Map<String, Set<Book>> catalog;
public BookCatalog(Map<String, Set<Book>> catalog) {
this.catalog = catalog;
}
public Set<Book> search(String key) {
if (!catalog.containsKey(key)) {
return null;
}
return catalog.get(key);
}
public static void main(String[] args) {
// 示例用的数据
Map<String, Set<Book>> catalog = new HashMap<>();
Set<Book> programmingBooks = Set.of(
new Book("Effective Java", "Joshua Bloch", 2008),
new Book("Clean Code", "Robert Martin", 2008)
);
Set<Book> fictionBooks = Set.of(
new Book("To Kill a Mockingbird", "Harper Lee", 1960),
new Book("1984", "George Orwell", 1949)
);
catalog.put("programming", programmingBooks);
catalog.put("fiction", fictionBooks);
// 使用示例
BookCatalog bookCatalog = new BookCatalog(catalog);
Set<Book> result = bookCatalog.search("programming");
if (result != null) {
for (Book book : result) {
System.out.println(book);
}
} else {
System.out.println("No results.");
}
}
}
class Book {
private String title;
private String author;
private int year;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
@Override
public String toString() {
return title + " by " + author + " (" + year + ")";
}
}
```
阅读全文