0
\$\begingroup\$

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);
}
\$\endgroup\$
1
\$\begingroup\$

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());
}
\$\endgroup\$
  • 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 Feb 11 '16 at 8:29
1
\$\begingroup\$

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);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.