简体   繁体   English

使用Maps.uniqueIndex和Guava时拒绝值

[英]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. 我想知道在使用Guava方法时是否可以丢弃一些值。

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". 因为我不能返回null或类似的东西,我将使用不相关语言的语言环境重定向到键“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? 是否有某种“/ dev / null”映射键,或者我是否总是需要在使用谓词之前/之后进行一些过滤?

Guava contributor here. 番石榴贡献者在这里。

Nope. 不。 Do a filter...or possibly more efficiently, just build the map yourself, and don't use Maps.uniqueIndex entirely. 做一个过滤器......或者可能更有效,只需自己构建地图,不要完全使用Maps.uniqueIndex It's probably simpler and shorter that way anyway. 无论如何,它可能更简单,也更短。

I want to add that if this issue is resolved you'll be able to do: 我想补充一点,如果这个问题得到解决,你将能够做到:

ImmutableMap<String, Locale> index = FluentIterable.from(availableLocales)
    .filter(NOT_BLANK_LANGUAGE)
    .uniqueIndex(GET_LANGUAGE);

public static Predicate<Locale> NOT_BLANK_LANGUAGE = new Predicate<Locale>() {
  @Override
  public boolean apply(Locale input) {
    return !StringUtils.isBlank(input.getLanguage());
  }
};

public static Function<Locale, String> GET_LANGUAGE = new Function<Locale, String>() {
  @Override
  public String apply(Locale input) {
    return input.getLanguage();
  }
};

which, with Java 8 lambdas, will be even more concise. 使用Java 8 lambdas,它将更加简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM