Android 用于放置和删除条目的捆绑迭代器

Android Bundle Iterator to Put and Remove Entries

我正在寻找一种方法来遍历 Bundle 对象中包含的条目。目前,我错误地使用了 For Each 方法:

for (String key : bundle.keySet()) {
    if ("videourl".equals(key.toLowerCase()) || "priority".equals(key.toLowerCase())) {
        // Save value to bundle using lowercase key value
        extras.putString(key.toLowerCase(), (String) extras.get(key));
        // Remove original version of this bundle entry
        extras.remove(key);
    }
}

上面显示的方法的问题在于它可能会在未来不确定的时间出现任意的、不确定的行为。

我见过 Map 对象的 Iterator 实现(例如 ):

for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
  Map.Entry<String, String> entry = it.next();
  if(entry.getKey().equals("test")) {
    it.remove();
  }
}

但是,我无法直接访问 Bundle 的条目,因此无法使用相同的方法。

如果 Iterators 可以与 Bundle 对象一起使用,请告诉我,或者请提出不同的方法。

不幸的是,我找不到使用迭代器向 Bundle 添加和删除条目的方法。我的解决方法是将要添加的条目保存到临时 Bundle 对象中,并将要删除的条目的原始键名保存到列表中。请看下面的代码:

// Loop through all messages and change the extras' key names to lowercase (only for keys of interest)
Bundle tempBundle = new Bundle();
ArrayList<String> keysToBeRemoved = new ArrayList<>();
Bundle extras = messages.get(i).getExtras();

for (String key : extras.keySet()) {
    // Check if key is not all lower case and if it is a key of interest
    if (!key.equals(key.toLowerCase()) && isKeyOfInterest(key)) {
        // Save value to bundle using lowercase key value
        tempBundle.putString(key.toLowerCase(), extras.getString(key));
        // Add original version of this key to a list for later deletion
        keysToBeRemoved.add(key);
    }
}

// Remove original entries from message extras
for (String originalKey : keysToBeRemoved) {
    extras.remove(originalKey);
}

// Add all new bundle entries to message extras
extras.putAll(tempBundle);

不过,如果有人知道如何将迭代器与 Bundle 一起使用,我很想知道!