简体   繁体   中英

How to remove all the keys whose values are either blank, null or empty

    Map<String, Object> m = new HashMap<>();
    ArrayList<String> str = new ArrayList<String>(Arrays.asList("Mohan", "Rohan", "", null));
    m.put("k1", str);
    m.put("k2", 43);
    m.put("k3", null);
    m.put("k4", "");
    System.out.println(m);
    Set<Map.Entry<String, Object>> entrySet = m.entrySet();
    Iterator<Map.Entry<String, Object>> itr = entrySet.iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Object> entry = itr.next();
        if (entry.getValue() == null || entry.getValue().toString().equals("")) {
            itr.remove();
        } else if (entry.getValue().getClass() == ArrayList.class) {
            ArrayList<String> arr = (ArrayList<String>) entry.getValue();
            for (int i = 0; i < arr.size(); i++) {
                if (arr.get(i) == null || arr.get(i).trim() == "") {
                    arr.remove(i);
                }
            }
        }
    }

I am getting stuck to remove empty and null values from arraylist Can anyone help me with this...

Your problem is that you remove element at index i , then the collection size changes, but you don't update index. This causes you to skip elements. To fix it you need to decrement index after removal:

arr.remove(i);
i--;

But it's not good idea to change indexes during iteration, it's error prone. It would be better to:

  1. Make iteration backwards
for (int i = arr.size() - 1; i >= 0; i--)

Like this you don't need to change index when removing

  1. Better would be to use Iterator.remove() , the same way you are removing elements from map

  2. Probably easiest solution - use Collection.removeIf(Predicate)

arr.removeIf(str -> str == null || str.trim().isEmpty());

To citate java doc - Removes all of the elements of this collection that satisfy the given predicate.

You could interrogate the map and remember items that match your criteria in a list. Then remove those items from the map like this:

Map<String, Object> m = new HashMap<>();
m.put("k3", null);
m.put("k4", "");

List<String> keysToRemove = new ArrayList();

m.forEach((key, value) -> {
  if (value == null ) {
    keysToRemove.add(key);
  }else if(value instanceof ArrayList){
    if(((ArrayList<String>) value).stream().filter(item -> item != null || !item.isEmpty()).count() == 0){
      keysToRemove.add(key);
    }
  }
});
for (String key : keysToRemove) {
  m.remove(key);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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