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);
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 21, 2016 at 11:59
\$\endgroup\$

2 Answers 2

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());
}
answered Jan 21, 2016 at 14:13
\$\endgroup\$
1
  • 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\$ Commented Feb 11, 2016 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);
answered Feb 11, 2016 at 8:29
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.