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

Jeeva D :

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

Naman :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105918&siteId=1