Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for value (list) existence in immutable map builder

Tags:

java

guava

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

like image 975
Xonar Avatar asked Jul 29 '16 17:07

Xonar


1 Answers

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);
like image 72
Xaerxess Avatar answered Sep 23 '22 10:09

Xaerxess