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

如何用Java8替代foreach循环?嵌套列表过滤代码转换问询

Refactoring Nested Loops to Java 8 Streams

Let's break this down step by step. First, let's fix the tiny syntax issue in your original code (you were missing a closing parenthesis in the if condition):

for(A aobj : branchList) {
    for(C cobj : aobj.getCList()) {
        if(!enteredBranchId.equals(cobj.getId())) {
            myList.add(aobj.getId());
        }
    }
}

Now, let's convert this to Java 8 stream style. There are two common approaches depending on whether you want to preserve the original duplicate behavior or avoid adding the same A ID multiple times.

Option 1: Match Original Behavior (Allow Duplicate IDs)

Your original code adds the A ID once for every C object in its list that doesn't match enteredBranchId. To replicate this exactly with streams:

branchList.stream()
    // For each A, stream its CList, filter non-matching Cs, map to A's ID
    .flatMap(a -> a.getCList().stream()
        .filter(c -> !enteredBranchId.equals(c.getId()))
        .map(c -> a.getId()))
    // Add each resulting ID to myList
    .forEach(myList::add);

How this works:

  • flatMap takes each A object, streams its CList, filters out the C objects that match enteredBranchId, then maps the remaining Cs to the parent A's ID. It flattens all these individual IDs into a single stream.
  • forEach(myList::add) adds every element from the stream to your list, just like the nested loops.

Option 2: Avoid Duplicate IDs (Add Each A ID Once)

If you only want to add an A's ID once if any of its C objects don't match enteredBranchId (a more common use case), use filter with anyMatch:

branchList.stream()
    // Keep only A objects where at least one C in CList doesn't match the ID
    .filter(a -> a.getCList().stream()
        .anyMatch(c -> !enteredBranchId.equals(c.getId())))
    // Map each qualifying A to its ID
    .map(A::getId)
    // Add each unique ID to myList
    .forEach(myList::add);

How this works:

  • filter checks if the CList of an A has any element that doesn't match enteredBranchId (using anyMatch).
  • map(A::getId) converts each qualifying A to its ID.
  • forEach adds each ID once, even if multiple Cs in the list meet the condition.

Pick the option that aligns with your actual requirements!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:27:15