Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reject values while using Maps.uniqueIndex with Guava

I'd like to know whether it's possible to discard some values when we use the Guava method.

public static Function<Locale, String> GET_LANGUAGE = new Function<Locale, String>() {
    @Override
    public String apply(Locale input) {
        return StringUtils.isBlank(input.getLanguage()) ? "NO_LANGUAGE" : input.getLanguage();
    }
};

Maps.uniqueIndex(availableLocales, GET_LANGUAGE);

I know I could have used a multimap since many locales can have the same language but it fits my needs actually.

For exemple, I'd like the locales without any language not to be in the output map. As I can't return null or things like that, I redirect the locales with non-relevant language to key "NO_LANGUAGE". The problem is that the value can still be retrieved.

Is there some kind of "/dev/null" map key, or will I always need to do some filter before/after using a predicate?

like image 605
Sebastien Lorber Avatar asked Sep 07 '25 20:09

Sebastien Lorber


1 Answers

Guava contributor here.

Nope. Do a filter...or possibly more efficiently, just build the map yourself, and don't use Maps.uniqueIndex entirely. It's probably simpler and shorter that way anyway.

like image 106
Louis Wasserman Avatar answered Sep 10 '25 11:09

Louis Wasserman