I have a map defined like this:
Map<String, List<SomeClass>> map = new HashMap<>();
I figured it would be nice to make it immutable, by using ImmutableMap.Builder
construct.
But in my case, when putting new elements in map, I need to first check for their existence, if list for given key doesn't exist, create it and add element to it:
for(final SomeClass elem : elements){
final String key = elem.getKey();
if(!map.containsKey(target)){
map.put(key, new LinkedList<SomeClass>());
}
map.get(key).add(elem);
}
If there target key in map, I need to create new list assigned to it, and then add element to that list.
Is there any way to make that map immutable without using unnecessary code like more loops to first initialize lists for target keys?
Btw. I'm using Java 7
You should use ListMultimap
here. Using ImmutableListMultimap.builder()
:
ImmutableListMultimap.Builder<String, SomeClass> builder = ImmutableListMultimap.builder();
for (final SomeClass elem : elements) {
final String key = elem.getKey();
builder.put(key, elem);
}
ImmutableListMultimap<String, SomeClass> multimap = builder.build();
But wait! There's built-in method for your use case - Multimaps#index(Iterable, Function)
:
ImmutableListMultimap<String, SomeClass> multimap = Multimaps.index(
elements,
new Function<SomeClass, String>() {
@Override public String apply(final SomeClass element) {
return element.getKey();
}
});
(In Java 8):
ImmutableListMultimap<String, SomeClass> multimap =
Multimaps.index(elements, SomeClass::getKey);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With