Working with lists and maps in Java
Iterating lists and removing objects
This examle shows 3 basic ways how to iterate through Lists (ArrayLists) and also how to remove objects from the list.
public static void iterateAndRemove1(List<String> list) {
for (int i = 0; i < list.size(); i++) {
if (i == 2) {
list.remove(i);
}
}
}
public static void iterateAndRemove2(List<String> list) {
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String s = it.next();
if (s.equals("BBB")) {
it.remove();
}
}
}
public static void iterateAndRemove3(List<String> list) {
for (String s : list) {
if (s.equals("BBB")) {
list.remove(s);
}
}
}
Iterating maps and removing objects
This examle shows some basic ways how to iterate through Maps (HashMap) and also how to remove objects from the map.
public static void iterateKeys(Map<String, Object> map) {
// the order of printed objects may not be preserved!
for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
String s = it.next();
System.out.println("key=" + s + " value=" + map.get(s));
}
}
public static void iterateValues(Map<String, Object> map) {
// the order of printed objects may not be preserved!
for (Iterator<Object> it = map.values().iterator(); it.hasNext();) {
Object s = it.next();
System.out.println("value=" + s);
}
}
public static void removeWithForEach(Map<String, Object> map) {
// don't do like this - this throws ConcurrentModificationException!
// you cannot remove while iterating through map
// use iterator instead
for (String s : map.keySet()) {
if (s.equals("BBB")) {
map.remove(s);
}
}
}
public static void removeWithIterator(Map<String, Object> map) {
// this works OK
for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
String s = it.next();
if (s.equals("BBB")) {
it.remove();
}
}
iterateKeys(map);
}