简体   繁体   English

将条目从一个Multimap复制到另一个Multimap

[英]Copy entries from one Multimap to another

This question relates to the Multimap from com.google.common.collect.Multimap. 此问题与com.google.common.collect.Multimap中的Multimap有关。

I have one Multimap, is there a simpler and more convenient way to copy entries whose key starts with a keyword to another temporary Multimap? 我有一个Multimap,是否有更简单,更方便的方法将密钥以关键字开头的条目复制到另一个临时Multimap? - below is my current solution. - 以下是我目前的解决方案。

private Multimap<String, String> copyDesiredMetadata(Multimap<String, String> metadata)
{
    Multimap<String, String> returnedMap = new CaseInsensitiveKeyMultimap<>();

    // Iterate through the entries in the metadata
    for (Map.Entry entry : metadata.entries()) {
        String key =entry.getKey().toString();
        // If the entry has the field key we are looking for add to returned map.
        if (key.startsWith("AAA") || key.startsWith("BBB") || key.startsWith("CCC") || key.startsWith("DDD")) {
            returnedMap.put(key, entry.getValue().toString());
        }
    }
    return returnedMap;
}

I believe "more convenient" should be defined but here a more functional approach : 我认为应该定义“更方便”,但这里有一个更实用的方法:

ImmutableMultimap<String, String> yourNewMap = metadata.entries()
            .stream()
            .filter(entry -> entry.getKey().matches("(AAA|BBB|CCC|DDD).*"))
            .collect(Collector.of(ImmutableMultimap.Builder<String, String>::new, 
                    ImmutableMultimap.Builder<String, String>::put, 
                    (left, right) -> {
                        left.putAll(right.build());
                        return left;
                    }, 
                    ImmutableMultimap.Builder::build));

Notice that I used ImmutableMultimap instead of CaseInsensitiveKeyMultimap as I don't know about this implementation but you should be able to adapt it easily. 请注意,我使用ImmutableMultimap而不是CaseInsensitiveKeyMultimap因为我不知道这个实现,但您应该能够轻松地进行调整。

Personally, I would extract the collector in an utility class so the code would look cleaner ... .collect(MoreCollectors.toCaseInsensitiveKeyMultimap()) 就个人而言,我会在实用程序类中提取收集器,因此代码看起来更干净...... .collect(MoreCollectors.toCaseInsensitiveKeyMultimap())

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

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