[英]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);
}
}
}
}
我無法從 arraylist 中刪除空值和 null 值 誰能幫我解決這個問題...
您的問題是您刪除了索引i
處的元素,然后集合大小發生變化,但您沒有更新索引。 這會導致您跳過元素。 要修復它,您需要在刪除后遞減索引:
arr.remove(i);
i--;
但是在迭代過程中更改索引並不是一個好主意,它很容易出錯。 最好是:
for (int i = arr.size() - 1; i >= 0; i--)
像這樣你不需要在刪除時更改索引
更好的方法是使用Iterator.remove()
,就像您從 map 中刪除元素一樣
可能是最簡單的解決方案 - 使用Collection.removeIf(Predicate)
arr.removeIf(str -> str == null || str.trim().isEmpty());
引用 java doc - Removes all of the elements of this collection that satisfy the given predicate.
您可以詢問 map 並記住列表中符合您條件的項目。 然后像這樣從 map 中刪除這些項目:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.