有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从ArrayList中删除空项

我正在从GeoCoder谷歌地图API检索地址,在将结果传递给Spinner对象之前,我需要从列表中删除所有空条目

我尝试了以下两种方法,但都没有效果:

locs.removeAll(Arrays.asList("", null));
locs.removeAll(Collections.singleton(null));

-

private List<Address> getAddress(double latitude, double longitude,int maxResults) {
    Geocoder gCoder = new Geocoder(getApplicationContext(),Locale.getDefault());
    try {
        locs = gCoder.getFromLocation(latitude, longitude, maxResults);
        locs.removeAll(Arrays.asList("", null));
        //locs.removeAll(Collections.singleton(null));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return locs;

}

共 (3) 个答案

  1. # 1 楼答案

    for(int i=0;i<list.size();i++) { if(list.get(i)==null||list.get(i).equals(""))// in case of string only otherwise only one检查就足够了 { 列表。移除(i); i ; `}

  2. # 2 楼答案

    试试这个

        List locs = new ArrayList();
        locs.add("");
        locs.removeAll(Arrays.asList("", null));
        System.out.println(locs.size());
    

    输出

    0
    

    还有这个

        locs.add("");
        locs.removeAll(Collections.singleton(null));
        System.out.println(locs.size());
    

    输出

    1
    

    这是有区别的

  3. # 3 楼答案

    用下面的代码遍历列表

        for (int i = 0; i < locs.size(); i ++){
            if (locs.get(i) == null){
                locs.remove(i);
                i  ;
            }
        }