Search code examples
javajava-streamnested-loops

Can we Merge these three nested for loops by using streams in java 8?


While trying to convert the following code by using Streams I ended up in some error. I couldn't convert it by using the streams. I couldn't merge the for loops by using Streams

The below code is the one which has to be changed by using streams.

     for (Admin ah : subProducers) {
                List<String> wns = ah.getAdminSitCodes().stream()
                        .map(new SitCodeMap()).map(Pair::getFirst)
                        .distinct().collect(Collectors.toList());

                for (String wn : wns) {
                    for (String value : values) {
                        if (wn.equals(value)) {
                            admin.add(ah);
                        }
                    }
                }
            }

I have tried as found below

     admin = subProducers.stream().map(sp-> sp.getAdminSitCodes().stream()
                  .map(new SitCodeMap())

     .map(Pair::getFirst).distinct()).collect(Collectors.toList())
                    .stream()
                   .filter(wns->values.stream().anyMatch(v- 
      >wns.equals(v)))
                   .collect(Collectors.toList());

Have to get this converted to a list using streams


Solution

  • You can make use of the Set collection for values and then complete the code as :

    List<Admin> admin = subProducers.stream()
            .filter(a -> a.getAdminSitCodes().stream()
                    .map(new SitCodeMap())
                    .map(Pair::getFirst) // assuming this is Stream<String>
                    .distinct()
                    .anyMatch(values::contains))
            .collect(Collectors.toList());