Traversal of Map
1. traverse key and value via Map.entryset
New Hashmap<>(); Map.put (1, ten); Map.put (2, 8); for (Map.entry<integer, integer> entry:map.entrySet ()) { + "----" + Entry.getvalue ());}
If the map you traverse is an empty object (null), the For-each loop will throw a java.lang.NullPointerException exception
2. Traverse key through Map.keyset () to traverse value through Map.values (), for cases where only the key or value in the map is required
New Hashmap<>(); Map.put (1, ten); Map.put (2, 8); for (Integer i:map.keyset ()) { System.out.println (i); } for (Integer i:map.values ()) { System.out.println (i); }
3. Traverse the map via iterator
Using generics
map<integer,integer> map =NewHashmap<>(); Map.put (1, 10); Map.put (2, 8); Iterator<map.entry<integer, integer>> iterator =Map.entryset (). iterator (); while(Iterator.hasnext ()) {Map.entry<integer, Integer> temp =Iterator.next (); System.out.println (Temp.getkey ()+ " ----- " +Temp.getvalue ()); }
Do not use generics
map<integer,integer> map = new hashmap<> ();
Map.put (1, 10);
Map.put (2, 8);
Iterator Iterator = Map.entryset (). Iterator ();
while (Iterator.hasnext ()) {
Map.entry Entry = (map.entry) iterator.next ();
Integer key = (integer) entry.getkey ();
Integer value = (integer) entry.getvalue ();
SYSTEM.OUT.PRINTLN (key + "-----" + value);
}
4. Find value by key ( low efficiency )
New Hashmap<>(); Map.put (1, ten); Map.put (2, 8); for (Integer key:map.keySet ()) { = map.get (key); + "-----" + value); }
the traversal of the list
1. Mode One
New Arraylist<>(); List.add (1); List.add (2); for (Integer i:list) { System.out.println (i); }
2. Mode II
New Arraylist<>(); List.add (1); List.add (2); = list.iterator (); while (Iterator.hasnext ()) { System.out.println (Iterator.next ()); }
3. Mode Three
New Arraylist<>(); List.add (1); List.add (2); for int i = 0; I < list.size (); i++ ) { System.out.println (List.get (i)); }
How Java collections are traversed