将多个集合合并为一个?
Combine severel collections into one?
我有以下代码:
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.我用java6
这个看起来更好看:
Collection<LinkedHashSet<String>> values = ((Map) userPreferenceValue).values();
Set<String> contraValues = Sets.newHashSet(Iterables.concat(values));
在Java6中我会推荐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();
我有以下代码:
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.我用java6
这个看起来更好看:
Collection<LinkedHashSet<String>> values = ((Map) userPreferenceValue).values();
Set<String> contraValues = Sets.newHashSet(Iterables.concat(values));
在Java6中我会推荐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();