Div
Div

Reputation: 33

Java 8 Streams: how can i stream another stream.How can i convert the code into java8 streams

Can someone please help me convert the below statements to Java8:

I have a hashmap like this:

private Map<String, Pair<List<XYZFiles>, List<XYZFiles>>> someMap;

I want to convert the below logic in java8:

private String searchFiles(String transmittedFileId) {

for (Pair<List<XYZFiles>, List<XYZFiles>> pair : someMap.values()) {
    List<XYZFiles> createdFilesList = pair.getKey();
    Optional<XYZFiles> xYZFiles= createdFilesList.stream()
                .filter(file -> 
                         file.getId().endsWith(transmittedFileId)).findFirst();
    if (xYZFiles.isPresent()) {
        return xYZFiles.get().getOriginId();
    }
  }
}

Upvotes: 2

Views: 954

Answers (1)

Sweeper
Sweeper

Reputation: 270890

return someMap.values().stream()
           .map(Pair::getKey)
           .flatMap(List::stream)
           .filter(file -> 
               file.getId().endsWith(transmittedFileId)
           ).findFirst().map(XYZFiles::getOriginId).orElse(null);

I think that should do it. It basically does it flat map, which flattens all those lists into one big stream and filters the whole thing.

Upvotes: 5

Related Questions