简体   繁体   中英

Java merging streams by common value

I have method like:

private X findMatchingValuesInStream(Stream<DocumentDto> a, Stream<FolderDto> b) {
    // TODO: return Pairs matched by documentDto.url and folderDto.url
}

I know that there is only one match by url field and i want to return a Pairs that's have the match.

So for example if we had documentDto with url="asasa" and some other fields set and folderDto with url="asasa" and some other fields set i want to return for example Pair of this elements.

Finally my method will return a List of these elements.

I am not sure how to do it with streams? I tried something like:

    a.filter(c -> b.anyMatch(d -> d.getUrl().equals(c.getUrl())))

But i don't know hot to create from it a Pair with c and d .

Don't use stream as your input. Streams are not holders for your data. Rather they are used as a means of processing data.

Another point to consider is that stream is NOT an Iterable and you won't be able to iterate over it. The Collection interface is a subtype of Iterable and has a stream method, so it provides for both iteration and stream access. Therefore, Collection or an appropriate subtype is generally the best return/input type for a public method.

First create a map using folders where key is the url and value is the folderDto. Then for each document look for the map to get the matching folder instance, and then create the Pair. I have used Map.Entry as a better alternative to Pair . If you prefer Pair , you may merely substitute it.

Here's how it looks.

private List<Entry<DocumentDto, FolderDto>> findMatchingValuesInStream(Collection<DocumentDto> a, Collection<FolderDto> b) {
    Map<String, FolderDto> folderByUrl = b.stream()
        .collect(Collectors.toMap(FolderDto::getUrl, Function.identity()));
    return a.stream()
        .map(d -> new AbstractMap.SimpleEntry<>(d, folderByUrl.get(d.getUrl())))
        .collect(Collectors.toList());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM