简体   繁体   English

Java 8 从 HashMap 中提取非空和非空值

[英]Java 8 extract non null and non empty value from HashMap

Let consider a below HashMap让我们考虑下面的HashMap

HashMap<String, String> map = new HashMap<String, String>();

I have values in map like我在地图中有值

map.put("model", "test");

Currently, if I want to get value from map I am doing目前,如果我想从地图中获取价值,我正在做

if(map!=null){
 if(map.get("model")!=null && !map.get("model").isEmpty()){
   //some logic
 }
}

Is there any better approach in Java 8 by using Optional or Lambdas to achieve the above condition?通过使用Optional或 Lambdas 来实现上述条件,Java 8 中是否有更好的方法?

First of all, your Map should not be null.首先,您的 Map 不应为空。 Never.从来没有。 It could be empty, but there's no reason for it to be null.它可能是空的,但没有理由让它为空。 So that eliminates the first null check.这样就消除了第一个空检查。

Now, unfortunately, Java doesn't have such a utility method, but several commonly used libs (apache commons, Guava, etc.) have it, or you can write it yourself, so it becomes:现在很遗憾,Java没有这样的实用方法,但是几个常用的libs(apache commons、Guava等)都有,也可以自己写,所以就变成了:

String model = map.get("model");
if (!Strings.isEmptyOrNull(model)) {
    // do somthing
}

Using Optional to wrap a nullable value as part of your logic is considered an antipattern.使用 Optional 将可空值包装为逻辑的一部分被视为反模式。 Optional is designed to be used as a return type. Optional 旨在用作返回类型。 So I wouldn't advide using it here.所以我不建议在这里使用它。

Also note that it feels like you're using a map to store attributes of an object If it is so, then consider defining a real class, with typed properties, instead of using a map.另请注意,感觉就像您在使用映射来存储对象的属性 如果是这样,那么请考虑定义一个具有类型化属性的真实类,而不是使用映射。

Not sure why you check if the map is null after just having created it, but here goes:不确定为什么在创建地图后检查地图是否为空,但这里是:

Optional.ofNullable(map)
    .map(m -> m.getOrDefault("model", "")) // Use an empty String if not present
    .filter(s -> !s.isEmpty())             // Filter all empty values
    .ifPresent(valueString -> {            // Check if value is present
        // Logic here
});

Or in one line:或者在一行中:

Optional.ofNullable(map).map(m -> m.getOrDefault("model", "")).filter(s -> !s.isEmpty()).ifPresent(valueString -> {
        // Logic here
});

Change ifPresent to map if you want to return something;如果要返回某些内容,请将ifPresent更改为map ie Optional of whatever you calculate.即您计算的任何内容都是可选的。

If you are interested in an Optional approach,如果您对Optional方法感兴趣,

You can wrap a map.get("model") value into an Optional.ofNullable and do filter work by the Predicate<String> value -> !value.isEmpty() :您可以将map.get("model")值包装到Optional.ofNullable ,并通过Predicate<String> value -> !value.isEmpty()进行过滤工作:

if (isNull(map)) { // import static java.util.Objects.isNull;
    return;        // to minimise nesting
}

Optional.ofNullable(map.get("model"))
        .filter(value -> !value.isEmpty())
        .ifPresent(value -> { ... });

If you've declared map as showing in your sample code then it won't be null and you don't need to check for it.如果您已将map声明为示例代码中所示,则它不会为null ,您无需检查它。 If you want to make sure then add an assertion:如果你想确保然后添加一个断言:

assert map != null;

Given you are testing for empty strings, a possible approach is to use the empty string as a default if the key is not present:鉴于您正在测试空字符串,如果键不存在,一种可能的方法是使用空字符串作为默认值:

if (!map.getOrDefault("model", "").isEmpty()) {
    ...
}

I think it's a shame that there was no method added to Map that returns an Optional rather than a null if the key isn't present.如果键不存在,我认为没有添加到Map方法返回Optional而不是null是一种耻辱。 Something like:类似的东西:

map.getOptional("model").filter(v -> !v.isEmpty()).ifPresent(v -> {
    ...
}

While optionals have been added there's been little rework of older APIs to deprecate methods that return null to mean "not present".虽然添加了可选项,但几乎没有对旧 API 进行修改以弃用返回null表示“不存在”的方法。

You can also try containsKey method.您也可以尝试 containsKey 方法。 For example:例如:

HashMap<String, String> map = new HashMap<String, String>();
map.put("model", "test");

 if(map.containsKey("model")){
   //some logic
 }

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

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