Saturday, March 12, 2016

Java : Looping (Iterator)

Looping (Iterator)

 

Iterator :

Collections = Lists(arraylist) , Set(HashSet -remove duplicates) , Map(similar to dictionary)
  1. Java iterator is an interface.
  2. belongs to collection framework
  3. allow us to traverse the the data element without bothering implementation. Ex : User may use array ,list etc.,
  4. Basically List and set collection provides the iterator ( ArrayList, LinkedList, and TreeSet etc)
  5. Map implementation such as HashMap doesn’t provide Iterator directly


Using Iterator

  1. Create an  iterator
  2. Have the loop iterate as long as hasNext( ) returns true.
  3. Within the loop, obtain each element by calling next( ).


Array List
ArrayList<Student> s= new ArrayList<Student>();   
s.add(new Student(Adam,98));    
s.add(new Student(Bob,65));           

for(int i=0;i<=s.size();i++)                //Noraml Loop
    System.out.println(s.get(i).name); 

for(Student s_loop:s)                          //Enhanced Loop                           
    System.out.println(s_loop.name);  

for (Iterator i=s.iterator();s.hasnext()){    //Iterator
    Student s_loop=(Student)i.next();
    System.out.println(s_loop.name);
    }

   
Array
Student[] s =new Student[2];
Student Adam=new Student("Adam",98);
Student Bob=new Student("Bob",67);

s[0]=Adam;
s[1]=Bob;

for(int i=0;i<=s.length-1;i++)
    Syste
m.out.println(s[i].name);


   
You can use Iterator Patten when you want similar implementation in both List and Array
1. ArrayList already comes ready with iterator so need to worry about that
2. We need to implement for Array or Class which uses array without changing the code.
(326pg -Design Patterns,Head First)
Or
1. Use Guava
Iterator<String> it = Iterators.forArray(array);
 

Examples :

1.  HashMap

//Use Java 1.8
HashMap m=new HashMap();
m.put(1, "01");
m.put(2, "02");

m.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));


or 
Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}


 2. Array List
ArrayList a=new ArrayList();   
a.add(1);
a.add("hi");

Iterator it=a.iterator();
while(it.hasNext()){
System.out.println(it.next());
}


3.HashSet
HashSet s=new HashSet();
s.add("hi");
s.add("hi");
s.add("abc");
s.add("bye");

Iterator i=s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}


Example 2


public class CrunchifyIterateThroughList {
public static void main(String[] argv) {

List<String> crunchifyList = new ArrayList<String>();

crunchifyList.add("eBay");
crunchifyList.add("Paypal");
crunchifyList.add("Google");
crunchifyList.add("Yahoo");
// iterate via "for loop"
for (int i = 0; i < crunchifyList.size(); i++) {
System.out.println(crunchifyList.get(i));
}
// iterate via "New way to loop"
for (String temp : crunchifyList) {
System.out.println(temp);
}
// iterate via "iterator loop"
Iterator<String> crunchifyIterator = crunchifyList.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println(crunchifyIterator.next());
}
// iterate via "while loop"
int i = 0;
while (i < crunchifyList.size()) {
System.out.println(crunchifyList.get(i));
i++;
}
// collection stream() util: Returns a sequential Stream with this collection as its source
crunchifyList.forEach((temp) -> {
System.out.println(temp);
});
}
}

No comments:

Post a Comment