You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Solution

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 null inputs (both the list and the author string) to avoid unexpected NullPointerExceptions.
  • Handling Null Authors: If some Book instances might have a null author field, adjust the filter condition to book != 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:18:21