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

Java作业:如何用Stream与Lambda表达式替代Iterator实现筛选

Convert Iterator to Java Streams & Lambdas

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 assume users is a Collection<User> like a List or Set) 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 only User objects where their first name exactly matches the input string.
  • .collect(Collectors.toList()): Takes all the filtered elements from the Stream and collects them into a List. If you specifically need an ArrayList (instead of any general List), 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:05:13