CodeHS技术需求:编写按作者筛选书籍的Java方法
Got it, let's solve this problem step by step. Here's how you can implement the filterBooks method properly, including both traditional and modern Java approaches:
First, let's start with the reference Book class (since it's provided, we'll define its core structure for context):
public class Book { private String title; private String author; public Book(String title, String author) { this.title = title; this.author = author; } // Required getter method to retrieve the book's author public String getAuthor() { return author; } // Optional: Override toString for easier debugging and output @Override public String toString() { return "Book{title='" + title + "', author='" + author + "'}"; } }
Approach 1: Traditional Iteration (Java 7 and below)
This approach uses an Iterator to safely remove non-matching books from the original list—this avoids the ConcurrentModificationException that would occur if you tried to remove elements directly in a for-each loop.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class BookFilter { public List<Book> filterBooks(List<Book> readingList, String author) { // Guard clauses to handle null inputs gracefully if (readingList == null || author == null) { return new ArrayList<>(); // Return empty list as a safe default } // Use Iterator to safely remove books not matching the target author Iterator<Book> bookIterator = readingList.iterator(); while (bookIterator.hasNext()) { Book currentBook = bookIterator.next(); // Compare authors; add a null check for book.getAuthor() if your data might have null values if (!author.equals(currentBook.getAuthor())) { bookIterator.remove(); } } // Return the modified original list return readingList; } }
Approach 2: Java 8+ Stream API (Modern, Clean Approach)
The Stream API simplifies this task significantly, and it returns a new list (leaving the original list unchanged—this is often preferred to avoid unintended side effects).
import java.util.List; import java.util.stream.Collectors; public class BookFilter { public List<Book> filterBooks(List<Book> readingList, String author) { // Guard clauses for null safety if (readingList == null || author == null) { return List.of(); // Java 9+ immutable empty list; use new ArrayList<>() for older versions } // Stream to filter matching books and collect them into a new list return readingList.stream() // Add null checks for book and book.getAuthor() if your dataset might contain nulls .filter(book -> book != null && author.equals(book.getAuthor())) .collect(Collectors.toList()); } }
Key Notes
- Null Safety: Always add checks for
nullinputs (both the list and the author string) to avoid unexpectedNullPointerExceptions. - Handling Null Authors: If some
Bookinstances might have anullauthor field, adjust the filter condition tobook != null && book.getAuthor() != null && author.equals(book.getAuthor())to prevent crashes. - Original List vs. New List: The traditional approach modifies the input list directly, while the Stream approach returns a new list. Choose based on your use case—preserve the original list if you need it later.
内容的提问来源于stack exchange,提问作者Jakarak

