如何用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?
- Chained filters make the second condition unreachable: After filtering for
User::isActive, your stream only contains active users. The subsequentfilter(user -> !user.isActive())will have zero elements to process, so thatpeekcall never runs. - No terminal operation: Stream intermediate operations (like
filter,peek) don't execute until a terminal operation (likeforEach,collect,count) is called. Your code doesn't trigger the stream at all, so none of thesetTextcalls actually modify youruserslist.
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
相关产品推荐
相关产品推荐

