2017-07-26 40 views
2

我想将Guava Multimap<String ,Collection<String>>转换成Map<String, Collection<String>>,但是在使用Multimaps.asMap(multimap)时出现语法错误。下面是一个代码:如何将Guava HashMultmap转换为java.util.Map

HashMultimap<String, Collection<String>> multimap = HashMultimap.create(); 
for (UserDTO dto : employees) { 
    if (dto.getDepartmentNames() != null) { 
     multimap.put(dto.getUserName().toString().trim(), dto.getDepartmentNames()); 
    } 
} 
Map<String, Collection<String>> mapOfSets = Multimaps.asMap(multimap); 

这是错误的截图: enter image description here

有人能指出哪里我做了一个错误?

+1

为什么不将'mapOfSets'定义为Map >'? – RealSkeptic

+0

我已经返回的方法是返回Map >,这样我需要相同的返回类型。 – user565

+0

我已经检查过我的所有进口都使用番石榴API而不是Apache – user565

回答

2

返回类型Multimaps.asMap(multimap)Map<String, <Set<Collection<String>>

Multimap可以保存同一个键的多个值。因此,当您想要从multimap转换为地图时,您需要为每个键保留值的集合,以防万一有一个键在地图中出现两次。

如果你想从MultiMap转换为Map,并在值集总和,你可以做到以下几点:

Multimaps.asMap(multimap).entrySet().stream() 
    .collect(Collectors.toMap(
       Map.Entry::getKey, 
       e->e.getValue().stream() 
         .flatMap(Collection::stream).collect(toSet()))); 
+0

@xentros感谢提示。它适用于Map >> mapOfSets = Multimaps.asMap(multimap);我仍然感到困惑,因为我的方法签名是不同的,所以我会如何得到Map >? – user565

+0

@ user565你了解我写的代码吗? – xenteros

+0

是的,我明白了。我的项目中有关于番石榴版本的问题。休息似乎是一个完美的实施。 – user565

0

我觉得你在这里做什么用Multimap错误。 Multimap<String, Collection<String>>大致相当于Map<String, Collection<Collection<String>>>,因此在使用asMap视图(例如{user1=[[IT, HR]], user2=[[HR]], user3=[[finance]]})时会导致嵌套收集。

你真正想要的是使用Multimap<String, String>(更具体:SetMultimap<String, String>相当于Map<String, Set<String>>),并使用Multimap#putAll(K, Iterable<V>)

SetMultimap<String, String> multimap = HashMultimap.create(); 
for (UserDTO dto : employees) { 
    if (dto.getDepartmentNames() != null) { 
     // note `.putAll` here 
     multimap.putAll(dto.getUserName().toString().trim(), dto.getDepartmentNames()); 
    } 
} 
Map<String, Set<String>> mapOfSets = Multimaps.asMap(multimap); 
// ex. {user1=[HR, IT], user2=[HR], user3=[finance]} 

使用Multimaps#asMap(SetMultimap)代替SetMultimap#asMap()是必要的,因为Java类型系统的限制(不能覆盖泛型中的泛型类型时):

Note: The returned map's values are guaranteed to be of type Set . To obtain this map with the more specific generic type Map<K, Set<V>> , call Multimaps.asMap(SetMultimap) instead.

相关问题