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

Java 8中如何用Stream修改列表元素字段:填充员工地址业务类型

Solution Using Java 8 Streams

Since your Address class is mutable (it has setters for fields), you can use Java 8 Streams to iterate over the list of addresses and update the businessType field based on businessCode directly. Here's how to do it cleanly:

Step 1: Define Your Business Code to Type Mapping

First, create a mapping of business codes to their corresponding types. Using a Map makes this lookup efficient and easy to maintain:

import java.util.Map;

// Define this as a static constant in your class (or wherever makes sense for your codebase)
private static final Map<String, String> BUSINESS_CODE_MAPPING = Map.of(
    "CODE001", "RESIDENTIAL",
    "CODE002", "COMMERCIAL",
    "CODE003", "TEMPORARY"
    // Add all your code-type pairs here
);

Step 2: Process the Addresses with Streams

Next, retrieve the address list from your Employee object, use a Stream to iterate over each address, and set the businessType using the mapping. We'll also handle potential nulls to avoid NullPointerException:

import java.util.Optional;

// Assume you have an Employee instance named 'employee'
Optional.ofNullable(employee.getAddresses())
    .ifPresent(addresses -> addresses.stream()
        .forEach(address -> {
            // Look up the type using the business code, default to "UNKNOWN" if the code isn't in our map
            String businessType = BUSINESS_CODE_MAPPING.getOrDefault(address.getBusinessCode(), "UNKNOWN");
            address.setBusinessType(businessType);
        })
    );

How This Works

  • Optional.ofNullable(employee.getAddresses()) safely handles the case where the addresses list might be null, preventing unexpected NPEs.
  • ifPresent(...) only runs the stream logic if the list actually exists.
  • addresses.stream() creates a Stream of Address objects to process.
  • forEach(...) applies the update logic to each Address: we look up the matching business type from our map (using getOrDefault to gracefully handle unknown codes) and set it via the class's setter method.

Notes

  • Even though Streams are often used for functional, non-mutating operations, modifying mutable objects' state (like updating a field via a setter) is acceptable here—we're not altering the source collection itself, just the objects inside it.
  • If you prefer not to use Optional, you can add an explicit null check instead:
    if (employee.getAddresses() != null) {
        employee.getAddresses().stream()
            .forEach(address -> {
                String businessType = BUSINESS_CODE_MAPPING.getOrDefault(address.getBusinessCode(), "UNKNOWN");
                address.setBusinessType(businessType);
            });
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:13:41