2016-01-21 105 views
0

我有以下代码:将仇恨集合合并为一个?

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

+1

“PS我用java 6”为什么? –

+1

如果你必须留在Java 6上,那么这段代码就没问题。 – Tom

+2

@tobias_k给客户的问题 – gstackoverflow

回答

3

这看起来更好:

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

在Java 6中,我会建议番石榴的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();