-3

How can I convert this code as per java8 having an inner list inside a parent list and do filtering?

for(A aobj: branchList) {
    for(C cobj : aobj.getCList()) {
        if(!enteredBranchId.equals(cobj.getId())
            myList.add(aobj.getId());
    }
}
Daniel Atlas
  • 1
  • 2
  • 5
  • Well, where did you run into a problem with Java streams? Do you know what a `flatMap` operation is? What a `collect` is supposed to do and what collectors are available? Did you try to use any and failed? – RealSkeptic Sep 09 '19 at 15:50
  • https://dzone.com/articles/3-reasons-why-you-shouldnt-replace-your-for-loops – trilogy Sep 09 '19 at 15:52
  • 1
    Vague title. Rewrite to summarize your specific technical issue. – Basil Bourque Sep 09 '19 at 15:58
  • @RealSkeptic - I did use a couple of functions but could not make the one needed. Any help with the code is helpful! – Daniel Atlas Sep 09 '19 at 16:13

1 Answers1

2
myList = branchList.stream()
           .map(b -> b.getSubBranches())  
           .flatMap(Collection::stream)
           .filter(sb -> !enteredBranchId.equals(sb.getBranchId()))
           .collect(Collectors.toList());
NiVeR
  • 9,644
  • 4
  • 30
  • 35
  • 1
    Shouldn't you be calling `getSubBranches()` in your `flatMap`? – Jacob G. Sep 09 '19 at 16:13
  • won't the getBranchId() will throw a compile-time exception? and so does the Collection::stream as the non-static method context error? – Daniel Atlas Sep 09 '19 at 16:18
  • @JacobG. true, for the `flatMap` to work the `branchList` is got tot be a `Collection>`, besides that, even if it would work, the answer does not even deal with class `C` in the question. Downvoting for this reason. – Naman Sep 09 '19 at 16:47
  • @JacobG. true, I forgot that step. @Naman This answer was done on the first version of the question. If you notice multiple edits were done, and the class `C` was added later on. – NiVeR Sep 10 '19 at 07:20
  • `map(b -> b.getSubBranches()) .flatMap(Collection::stream)` can be converted to `flatMap(b -> b.getSubBranches().stream())` – Naman Sep 10 '19 at 13:20