First, when learning ArrayList and map, the records of the common traversal methods are as follows:
Second, the following source code:
Package com.study.in.myself;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
public class Study16 {
public static void Main (String [] args) {
Several methods of traversing ArrayList
Create a ArrayList object and shape it to a string type
list<string> list = new arraylist<string> ();
List.add ("Hello");
List.add ("World");
List.add ("Learning iterator");
First traversal method for loop
for (int i =0; i<list.size (); i++) {
HashMap map = (HASHMAP) list.get (i);
System.out.println (List.get (i));
}
The second traversal method iterates the linked list into array-related content
String[] Strarray=new string[list.size ()];
List.toarray (Strarray);
for (int i= 0; i < strarray.length;i++) {
System.out.println (Strarray[i]);
}
The third traversal method enhances the For loop
for (String str:list) {
System.out.println (str);
}
The fourth traversal method uses iterators to traverse
iterator<string> ite = List.iterator ();
while (Ite.hasnext ()) {
System.out.println (Ite.next ());
}
Several ways to traverse map
hashmap<string,string> map = new hashmap<string,string> ();
Map.put ("1", "Learning map with put value");
Map.put ("2", "Learning Map Traversal method");
Map.put ("3", "Hello World");
The first traversal method is commonly used by Map.get (key) two times
For (String Key:map.keySet ()) {
System.out.println ("Key" +key+ "value" +map.get (key));
}
The second traversal method uses iterator to traverse key and value through Map.entryset: (iterator traversal)
Iterator<map.entry<string, string>> it = Map.entryset (). Iterator ();
while (It.hasnext ()) {
map.entry<string, string> Entry = It.next ();
System.out.println ("Key" +entry.getkey () + "value" +entry.getvalue ());
}
The third method iterates through the Map.entryset key and value recommendations, especially when the capacity is large
For (map.entry<string, string> entry:map.entrySet ()) {
System.out.println ("Key" +entry.getkey () + "value" +entry.getvalue ());
}
The fourth method iterates through all of the value through Map.values (), but cannot traverse key with caution
For (String v:map.values ()) {
System.out.println ("value" +v);
}
}
}
Common traversal methods for ArrayList and maps in Java (learn notes for later query)