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

如何用Java 8 Stream根据条件为对象列表设置值(含if-else逻辑)

How to handle if-else conditions when setting values for a list of objects using Java 8 Streams API?

Let's break down the issues with your current code first, then fix it properly:

What's wrong with your existing code?

  1. Chained filters make the second condition unreachable: After filtering for User::isActive, your stream only contains active users. The subsequent filter(user -> !user.isActive()) will have zero elements to process, so that peek call never runs.
  2. No terminal operation: Stream intermediate operations (like filter, peek) don't execute until a terminal operation (like forEach, collect, count) is called. Your code doesn't trigger the stream at all, so none of the setText calls actually modify your users list.

Correct implementations

Since you're modifying the existing User objects in your list, here are the simplest, most readable approaches:

Option 1: Use forEach with inline if-else (most straightforward)

List<User> users = userDao.getAllByCompanyId(companyId);
users.stream()
    .filter(Objects::nonNull) // Guard against null entries
    .forEach(user -> {
        if (user.isActive()) {
            user.setText("ABC");
        } else {
            user.setText("XYZ");
        }
    });

forEach is a terminal operation that triggers the stream execution, and putting the if-else logic in one lambda handles both cases without splitting your stream.

Option 2: Use peek with a terminal operation (if you prefer peek syntax)

If you want to stick with peek, you just need to add a terminal operation to trigger the stream:

users.stream()
    .filter(Objects::nonNull)
    .peek(user -> {
        user.setText(user.isActive() ? "ABC" : "XYZ");
    })
    .count(); // Terminal operation to run the stream

We use count() here because we don't need the result—it just forces the stream to process all elements.

Bonus: Create new User objects (instead of modifying originals)

If you want to keep your original list unchanged and create a new list of updated users, use map:

List<User> updatedUsers = users.stream()
    .filter(Objects::nonNull)
    .map(user -> {
        // Create a new User instance to avoid modifying the original
        User updatedUser = new User();
        updatedUser.setId(user.getId());
        updatedUser.setName(user.getName());
        updatedUser.setActive(user.isActive());
        updatedUser.setText(user.isActive() ? "ABC" : "XYZ");
        return updatedUser;
    })
    .collect(Collectors.toList());

内容的提问来源于stack exchange,提问作者Newbie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:19:27