【问题标题】:Combine severel collections into one?将几个集合合二为一?
【发布时间】:2016-04-27 16:13:56
【问题描述】:

我有以下代码:

Object value = methodOutOfMyControl();        
Collection<LinkedHashSet<String>> values = ((Map) value).values();
Set<String> strings = new HashSet<String>();
for (LinkedHashSet<String> set : values) {
    strings.addAll(set);
}

有没有办法更简洁地重写这段代码?

P.S.我用的是java 6

【问题讨论】:

  • "P.S. 我使用 java 6" 为什么?
  • 如果你必须继续使用 Java 6,那么这段代码就可以了。
  • @tobias_k 向客户提问
  • 你可以使用Iterables.concat,但这只会给你一个Iterable...我认为没有使用Guava的更清洁的解决方案。当然,如果您经常需要这样做,您可以只编写一个辅助方法。

标签: java collections guava


【解决方案1】:

在 Java 6 中我会推荐 Guava 的 FluentIterable:

Object value = methodOutOfMyControl();
Collection<LinkedHashSet<String>> values = ((Map) value).values();

//transformAndConcat is similar to Java 8, Stream.flatMap
final ImmutableSet<String> set = FluentIterable.from(values)
      .transformAndConcat(Functions.identity()).toSet();

或者如果你真的想要一行:

 final ImmutableSet<String> set = FluentIterable.from(
            ((Map<?, LinkedHashSet<String>>) this.methodOutOfMyControl()).values())
        .transformAndConcat(Functions.identity())
        .toSet();

【讨论】:

    【解决方案2】:

    这看起来更好:

     Collection<LinkedHashSet<String>> values = ((Map) userPreferenceValue).values();
     Set<String> contraValues = Sets.newHashSet(Iterables.concat(values));
    

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2022-06-27
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多