Java作业:如何用Stream与Lambda表达式替代Iterator实现筛选
Hey there! Let's refactor your Iterator-based code to use Java Streams and Lambdas—it's way more concise, readable, and aligns with modern Java practices.
First, let's recap what your original code does: it iterates over the users collection, filters out any User whose firstName matches the input, collects those matches into an ArrayList, and returns it. Here's how to do the exact same thing with Streams:
import java.util.List; import java.util.stream.Collectors; static List<User> getUsers(String firstName) { return users.stream() // Filter users where firstName matches the input .filter(user -> user.getFirstName().equals(firstName)) // Collect the filtered users into a List .collect(Collectors.toList()); }
Breakdown of each step:
users.stream(): Converts your original collection (I assumeusersis aCollection<User>like aListorSet) into a Stream, which lets us chain functional operations..filter(user -> user.getFirstName().equals(firstName)): This Lambda expression replaces your while-loop's conditional check. It tells the Stream to keep onlyUserobjects where their first name exactly matches the input string..collect(Collectors.toList()): Takes all the filtered elements from the Stream and collects them into aList. If you specifically need anArrayList(instead of any generalList), you can swap this with:.collect(Collectors.toCollection(ArrayList::new))
A quick safety tip:
If there's a chance firstName could be null, or user.getFirstName() might return null, using Objects.equals() will prevent a NullPointerException:
.filter(user -> Objects.equals(user.getFirstName(), firstName))
That's it! This code does exactly what your original Iterator version did, but with less boilerplate and a more declarative style.
内容的提问来源于stack exchange,提问作者TrkDgnr

