@Test
public void removeElementFromMap()
{
Map<Integer, String> test = new HashMap<Integer, String>();
test.put(1, "a");
test.put(2, "b");
test.put(3, "c");
test.put(4, "d");
Iterator<Entry<Integer, String>> it = test.entrySet().iterator();
int key = 0;
while (it.hasNext())
{
key = it.next().getKey();
if (key == 1)
{
it.remove();
}
}
System.out.println(test);
}
删除List集合元素:
@Test
public void removeElementFromList()
{
List<Integer> testList = new ArrayList<Integer>();
testList.add(1111);
testList.add(2222);
testList.add(3333);
testList.add(4444);
Iterator<Integer> it = testList.iterator();
int value = 0;
while (it.hasNext())
{
value = it.next();
if (value == 1111)
{
it.remove();
}
}
}
本文提供了两个Java示例,展示了如何从HashMap中移除指定键值对以及如何从ArrayList中移除特定元素。通过迭代器安全地进行元素移除,避免了在遍历过程中直接修改集合导致的并发修改异常。
1548

被折叠的 条评论
为什么被折叠?



