这个问题与com.google.common.collect.Multimap中的Multimap有关。
我有一个Multimap,是否有一种更简单,更方便的方法将键以关键字开头的条目复制到另一个临时Multimap?-以下是我当前的解决方案。
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;
}
我认为应该定义“更方便”,但是这里有一个更实用的方法:
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));
请注意,我使用ImmutableMultimap
而不是CaseInsensitiveKeyMultimap
因为我不了解此实现,但是您应该能够轻松地对其进行调整。
就我个人而言,我会将收集器提取到一个实用程序类中,以便代码看起来更整洁…… .collect(MoreCollectors.toCaseInsensitiveKeyMultimap())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句