[java foundation] collection traversal summary in java

public static void main(String[] args) {
// list collection traversal
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("aaa");
list.add("aba");
list.add("aaa");


Iterator it = list.iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("Use Iterator to traverse mode one" + str);
}


for (Iterator it2 = list.iterator(); it2.hasNext();) {
String str1 = (String) it2.next();
System.out.println("Use Iterator to traverse method two"+str1);
}


for (int a = 0; a < list.size(); a++) {
System.out.println("Use a normal for loop to traverse"+list.get(a));
}


for (String str : list) {// The iterator traversal method is actually called internally. This loop method has other limitations and is not recommended.
System.out.println("Enhanced with for loop"+str);
}


//      hashmap collection traversal
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
map.put("4", "value4");
// The first type: common use, secondary value
System.out.println("\n Traverse key and value through Map.keySet: ");
for (String key : map.keySet()) {
System.out.println("1111" + map.keySet());
System.out.println("Key: " + key + " Value: " + map.get(key));
}


// The second: recommended, especially when the capacity is large
System.out.println("\ntraverse key and value through Map.entrySet");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key=" + entry.getKey() + "\nvalue=" + entry.getValue());
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812358&siteId=291194637