简体   繁体   English

Java通过通用值合并流

[英]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. 我知道按url字段只有一个匹配项,我想返回一个具有匹配项的对。

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. 因此,例如,如果我们设置了documentDtourl="asasa"并设置了其他字段,而folderDto设置了url="asasa"并设置了其他字段,我想返回此元素对。

Finally my method will return a List of these elements. 最后,我的方法将返回这些元素的List

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 . 但是我不知道如何用cd来创建Pair

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. 另一点要考虑的是,流不是Iterable ,你将无法遍历它。 The Collection interface is a subtype of Iterable and has a stream method, so it provides for both iteration and stream access. Collection接口是Iterable的子类型,并具有stream方法,因此它提供迭代和流访问。 Therefore, Collection or an appropriate subtype is generally the best return/input type for a public method. 因此,对于公共方法,Collection或适当的子类型通常是最佳的返回/输入类型。

First create a map using folders where key is the url and value is the folderDto. 首先使用文件夹创建一个地图,其中key是url,值是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 . 我使用Map.Entry作为Pair的更好替代。 If you prefer Pair , you may merely substitute it. 如果您更喜欢Pair ,则可以只替换它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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