【问题标题】:How to convert "Hashmap values of List type" into Set?如何将“List类型的Hashmap值”转换为Set?
【发布时间】:2017-01-28 09:16:41
【问题描述】:

如何在 Map 中连接“值列表”以创建单个列表,然后传递给另一个方法:

Map<Long,List<Long>> activities = new HashMap();
for(Something s: something){
  activities .put(prosessLongID, listOfSubProcesses);
} //There are 5 something and for each there are 2 List of Subprocesses which makes 10 Subprocesses

我想从上面的 Map 连接子流程列表以创建一个集合:

 ImmutableSet.copyOf(listOfSubProcesses_ForAllSomething) //com.google.common.collect

Map 中是否有任何方法可以返回单个列表中的所有子进程列表,我可以通过上述方法传递?

注意:我收到了@Eran 关于 Java 8 的回复,感谢您的回复。但请考虑 Java 6 和除循环之外的解决方案。我有 APache Commons 和 Guava 的设施。 :)

【问题讨论】:

  • 有一个方法Collection&lt;V&gt; values(),你需要做的就是查看文档...

标签: java list collections hashmap guava


【解决方案1】:

如果您不能使用 Java 8 Stream,请使用 Guava 的 FluentIterable(和 @Lukas 在评论中提到的 Map#values()):

ImmutableSet<Long> subprocessIds = FluentIterable.from(activities.values())
        .transformAndConcat(Functions.identity())
        .toSet();

FluentIterable#transformAndConcat 等价于Stream#flatMap,标识函数实际上什么都不做,所以它是从@Eran 的Java 8 对Guava 和Java 7 的直接翻译。

您也可以使用Iterables#concat 来实现相同的结果,而无需流畅的调用:

ImmutableSet<Long> subprocessIds = ImmutableSet.copyOf(
        Iterables.concat(activities.values()));

但是你真正想做的是使用正确的数据结构,这里:ListMultimap(或者甚至可能是SetMultimap?):

ListMultimap<Long, Long> activities = ArrayListMultimap.create();
activities.putAll(1L, ImmutableList.of(2L, 32L, 128L));
activities.put(3L, 4L);
activities.put(3L, 8L);

因为Multimap#values() 为您提供所需的内容(如Collection 视图,因此如有必要,请复制到Set):

ImmutableSet<Long> subprocessIds = ImmutableSet.copyOf(activities.values());

【讨论】:

    【解决方案2】:

    您可以使用 Java 8 Streams API 将所有 Lists 收集到一个 Stream 中,然后再收集到一个 List 中:

    List<Long> listOfSubProcesses_ForAllSomething = 
        activities.values().stream().flatMap(List::stream).collect(Collectors.toList());
    

    【讨论】:

    • 谢谢。但我现在还没有使用 Java-8。支持 Java 8 的解决方案。Java 6 怎么样
    • @fatherazrael 然后使用循环和 addAll 将每个列表的元素添加到单个列表中。
    • 我明白了。 Guava 或 Apache Common 中没有任何快捷方式或库方法吗?
    • @fatherazrael 可能有。我对番石榴不熟悉。
    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多