File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ package me .ramswaroop .misc ;
2+
3+ import java .util .*;
4+
5+ import static java .lang .System .out ;
6+
7+ /**
8+ * Created by IntelliJ IDEA.
9+ * <p/>
10+ * All possible ways of iterating different collections in Java.
11+ *
12+ * @author: ramswaroop
13+ * @date: 10/16/15
14+ * @time: 9:24 AM
15+ */
16+ public class CollectionIteration {
17+
18+ public static void main (String a []) {
19+ List <Integer > list = new ArrayList <>();
20+ list .add (1 );
21+ list .add (2 );
22+ list .add (3 );
23+ // 1st way
24+ Iterator <Integer > iterator = list .iterator ();
25+ while (iterator .hasNext ()) {
26+ out .println ("List: " + iterator .next ());
27+ }
28+ // 2nd way
29+ for (int i = 0 ; i < list .size (); i ++) {
30+ out .println ("List: " + list .get (i ));
31+ }
32+
33+ Map <String , Integer > hashMap = new HashMap <>();
34+ hashMap .put ("one" , 1 );
35+ hashMap .put ("two" , 2 );
36+ hashMap .put ("three" , 3 );
37+ // 1st way
38+ Iterator <Map .Entry <String , Integer >> iterator1 = hashMap .entrySet ().iterator (); // iterator only iterates on
39+ // lists or set and not on maps
40+ while (iterator1 .hasNext ()) {
41+ Map .Entry <String , Integer > entry = iterator1 .next ();
42+ out .println ("HashMap: " + entry .getKey () + "->" + entry .getValue ());
43+ }
44+ // 2nd way
45+ for (Map .Entry <String , Integer > entry : hashMap .entrySet ()) { // entrySet() returns a Set of Entry objects
46+ // stored in HashMap
47+ out .println ("HashMap: " + entry .getKey () + "->" + entry .getValue ());
48+ }
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments