如何用Java8替代foreach循环?嵌套列表过滤代码转换问询
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:
flatMaptakes eachAobject, streams itsCList, filters out theCobjects that matchenteredBranchId, then maps the remainingCs to the parentA'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:
filterchecks if theCListof anAhas any element that doesn't matchenteredBranchId(usinganyMatch).map(A::getId)converts each qualifyingAto its ID.forEachadds each ID once, even if multipleCs in the list meet the condition.
Pick the option that aligns with your actual requirements!
内容的提问来源于stack exchange,提问作者Daniel Atlas

