Is there a way to rewrite this code to make it more laconic? I'm using Java 6.
Object value = methodOutOfMyControl();
Collection<LinkedHashSet<String>> values = ((Map) value).values();
Set<String> strings = new HashSet<String>();
for (LinkedHashSet<String> set : values) {
strings.addAll(set);
}
2 Answers 2
I feel that sometimes inlining some values makes things a little more readable. But in terms of overall compactness, this isn't that much better. Here is what I would probably write
Map value = (Map)methodOutOfMyControl();
Set<String> strings = new HashSet<String>();
for (Map.Entry<Object, LinkedHashSet<String>> set : value.entrySet()) {
strings.addAll(set.getValue());
}
-
1\$\begingroup\$ If possible, supply the instantiation of the set with an educated guess of the number of elements to support.
Map.entrySet()
may be costly, and I don't see it used to advantage (avoid lookups) here. \$\endgroup\$greybeard– greybeard2016年02月11日 08:29:12 +00:00Commented Feb 11, 2016 at 8:29
While the cast to Map anything to Collection enables the use of a foreach loop, it wouldn't exactly express my intention (values better map to Collections containing Strings, only)
int MEMBERS_TO_EXPECT = 12345;
Set<String> strings = new HashSet<>(MEMBERS_TO_EXPECT);
for (Collection more : ((Map<?, Collection>) value).values())
strings.addAll(more);
// if modifications to strings shall be caught
strings = Collections.unmodifiableSet(strings);