使用自定义值集合类型创建Commons Collections MultiValueMap

Rya*_*tts 5 java generics apache-commons-collection

Apache Commons Collections库的4.0版本增加了泛型支持.我无法转换代码以利用它:

我想要一个MultiValueMap以字符串作为键,以及字符串的集合作为值.但:

  1. 键应该保留插入顺序(所以我通过装饰来创建多值映射LinkedHashMap)
  2. 每个键的值应该是唯一的并保留插入顺序(所以我希望值Collection类型为a LinkedHashSet).

我能得到的最接近的是:

MultiValueMap<String, String> orderedMap = MultiValueMap.multiValueMap(
    new LinkedHashMap<String, Collection<String>>(), 
    LinkedHashSet.class
);
Run Code Online (Sandbox Code Playgroud)

但是这会产生错误:

multiValueMap(Map<K,? super C>, Class<C>)类型中 的方法MultiValueMap不适用于参数 (LinkedHashMap<String,Collection<String>>, Class<LinkedHashSet>)

所以现在我在仿制药地狱.任何建议都是最受欢迎的.

在4.0版之前,我通过以下方式实现了这一目标:

MultiValueMap orderedMap = MultiValueMap.decorate(
    new LinkedHashMap<>(), 
    LinkedHashSet.class
);
Run Code Online (Sandbox Code Playgroud)

简单!我提供了LinkedHashMap使用MultiValueMap行为进行装饰,并指定LinkedHashSet要用作值的collection()的类型.但是,这需要铸造,当我打电话put()get(),所以我希望能够使用4.0提供的新的通用版本.

Rya*_*tts 5

我咨询了Apache Commons Collections 邮件列表,在那里向我解释说MultiValueMap已知缺少接口,但将在版本4.1中进行修改(请参阅此处了解JIRA问题和相关讨论).

所以在未来我们可能会有更好的解决方案,但与此同时,正如Rohit Jain在他的回答中提到的那样,我们将不得不压制一些警告.但是,由于类型安全的关键方面是MultiValueMap(不是自定义集合类型),实现此目的的最简单方法是:

@SuppressWarnings({ "rawtypes", "unchecked" })
MultiValueMap<String, String> orderedMap = 
    MapUtils.multiValueMap(new LinkedHashMap(), LinkedHashSet.class);
Run Code Online (Sandbox Code Playgroud)

注意使用MapUtils工厂方法,而不是MultiValueMap我在原始问题中使用的更直接.