Java 检查地图的空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18378934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:02:14  来源:igfitidea点击:

Check null value of map

java

提问by commit

I am getting mapas result and when I am getting value I need to convert it to Stringlike below:

我得到map了结果,当我得到价值时,我需要将其转换为String如下所示:

a.setA(map.get("A").toString());

but if it returns nullthan it throws nullPointerException, so I change it with below:

但是如果它返回的null比抛出的要多nullPointerException,那么我将其更改为以下内容:

a.setA(map.get("A")!=null?map.get("A").toString():"");

but there are more than 20 fields for that I am doing the same so I just want to do like below:

但是有超过 20 个字段,我正在做同样的事情,所以我只想像下面那样做:

String val = "";
a.setA(val=map.get("A")!=null?val.toString():"");

but it returns blankall time, I have just simple question is can't I use variable like this? or is there any other option for doing the same?

但它一直返回blank,我有一个简单的问题是我不能使用这样的变量吗?或者还有其他选择吗?

采纳答案by JB Nizet

Use a method. And avoid calling get()twice:

使用一种方法。并避免调用get()两次:

private String valueToStringOrEmpty(Map<String, ?> map, String key) {
    Object value = map.get(key);
    return value == null ? "" : value.toString();
}

...

...

String a = valueToStringOrEmpty(map, "A");
String b = valueToStringOrEmpty(map, "B");

Now repeat after me: "I shall not duplicate code".

现在跟我重复一遍:“我不会重复代码”。

回答by morgano

Problem is that valwont get the value you want until map.get("A")!=null?val.toString():""is evaluated, try this instead:

问题是valmap.get("A")!=null?val.toString():""评估之前不会得到你想要的值,试试这个:

String val = "";
a.setA((val=map.get("A"))!=null?val.toString():"");

so you get sure that val=map.get("A")evaluates before the whole thing.

所以你可以确保val=map.get("A")在整个事情之前进行评估。

回答by Abubakkar

Why don't you create a util method to this like:

为什么不创建一个 util 方法,例如:

public String getMapValue(Map m, String a){

    String s = m.get(a);
    if(s == null)
        return "";
    else
        return s;
}

Now you just need to call this method:

现在你只需要调用这个方法:

String val = getMapValue(map,"A");
a.setA(val);

回答by Ruchira Gayan Ranaweera

You can try this

你可以试试这个

    Map<String,String> map=new HashMap<>();
    Set<String> keySet=map.keySet();
    Iterator it=keySet.iterator();
    while (it.hasNext()){
       if(map.get(it)!=null){
           a.setA(map.get(it).toString());
       }else{   
           a.setA(null);
       }
    }

回答by benez

with Java 8 you can do the following:

使用 Java 8,您可以执行以下操作:

a.setA(map.getOrDefault("A", "").toString());