如何从 ArrayList 中排除空元素?

//This code for mapping the elements inside xml tag  

public static String getLeukemiaInvolvement(String val) {

    BiMap<String, String> map = HashBiMap.create();

    map.put("01", "6");

    map.put("02", "7");

    map.put("03", "8");

    map.put("04", "9");

    map.put("05", "3");


    return map.inverse().get(val);

}


for (String data : getListStringValForElementTag(element, "organ-involvement1")) {

        if(data != null) {

            sectionAmlAllMds.getOrganInvolvement1().add(Pris3BMdmMapper.getLeukemiaInvolvement(data));

        }


    }

如何确保我的输出不包含空元素?我已经对空元素进行了检查,但它不起作用。我的输出是:


 "organInvolvement1": ["01", "04", null, null, "05"]

此代码将读取 XML 标记“organ-involvement1”内的元素数组列表:


getListStringValForElementTag(element, "organ-involvement1")

谢谢


慕斯709654
浏览 263回答 3
3回答

温温酱

看起来在这种情况下,data不是 null 但它的值是null。试试这个:-if(data != null && Pris3BMdmMapper.getLeukemiaInvolvement(data) != null) {...}

哈士奇WWW

您可以编写一个实用方法来从集合中排除空值:static void removeNulls(Collection<?> c) {&nbsp; &nbsp; while(c.remove(null)) {&nbsp; &nbsp; &nbsp; &nbsp; // Do Nothing&nbsp; &nbsp;}}然后,在需要从集合中删除 exclude 元素时调用它:public static void main(String[] args) {&nbsp; &nbsp; List<String> colors = new ArrayList<>();&nbsp;&nbsp; &nbsp; Collections.addAll(colors, "red", null, "blue", "green", null);&nbsp; &nbsp; removeNulls(colors);&nbsp; &nbsp; System.out.println(colors);}

繁星点点滴滴

您还可以覆盖该add方法。但它可能会过度设计:List<String> list = new ArrayList<String>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public boolean add(String e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (e == null) return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return super.add(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java