Accessing collections/use of an Iterator

Accessing collections
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.

  1. Using Iterator interface
  2. Using ListIterator interface
  3. Using for-each loop
1. Accessing elements using Iterator: - Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.
import java.util.*;
Example: -
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
Iterator it = ar.iterator();
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Output: -
C:\java\word>javac Test_Iterator.java
C:\java\word>java Test_Iterator
ab bc cd de
2. Accessing element using ListIterator: - ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.
Example: -
import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
ListIterator litr = ar.listIterator();
while(litr.hasNext())
{
System.out.print(litr.next()+" ");
}
while(litr.hasPrevious())
{
System.out.print(litr.next()+" ");
}
}
}
Output: -
C:\java\word>javac Test_Iterator.java
C:\java\word>java Test_Iterator
ab bc cd de
de cd bc ab
3. Using for-each loop: - for-each version of for loop can also be used for traversing each element of a collection. But this can only be used if we don't want to modify the contents of a collection and we don't want any reverse access. for-each loop can cycle through any collection of object that implements Iterable interface.
Example: -
import java.util.*;
class ForEachDemo
{
public static void main(String[] args)
{
LinkedList< String> ls = new LinkedList< String>();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
for(String str : ls)
{
System.out.print(str+" ");
}
}
}
Output: -
C:\java\word>javac ForEachDemo.java
C:\java\word>java ForEachDemo
a b c d
Comparator
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.
The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.
Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.
For example, suppose one adds two elements a and b such that (a.equals(b) && c.compare(a, b) != 0) to an empty TreeSet with comparator c. The second add operation will return true (and the size of the tree set will increase) because a and b are not equivalent from the tree set's perspective, even though this is contrary to the specification of the Set.add method.
Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
For the mathematically inclined, the relation that defines the imposed ordering that a given comparator c imposes on a given set of objects S is:
{(x, y) such that c.compare(x, y) <= 0}.
The quotient for this total order is:
{(x, y) such that c.compare(x, y) == 0}.
It follows immediately from the contract for compare that the quotient is an equivalence relation on S, and that the imposed ordering is a total order on S. When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the ordering is the equivalence relation defined by the objects' equals(Object) method(s):
{(x, y) such that x.equals(y)}.
Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.
Example: -
import java.util.*;
class Person{
int age;
String name;
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
class AgeComparator implements Comparator{
public int compare(Object ob1, Object ob2){
int ob1Age = ((Person)ob1).getAge();
int ob2Age = ((Person)ob2).getAge();
if(ob1Age > ob2Age)
return 1;
else if(ob1Age < ob2Age)
return -1;
else
return 0;
}
}
class ComparatorExample{
public static void main(String args[]){
Person person[] = new Person[3];
person[0] = new Person();
person[0].setAge(35);
person[0].setName("A");
person[1] = new Person();
person[1].setAge(30);
person[1].setName("B");
person[2] = new Person();
person[2].setAge(32);
person[2].setName("C");
System.out.println("Order of person before sorting is");
for(int i=0; i < person.length; i++){
System.out.println( person[i].getName() + "\t" + person[i].getAge());
}
Arrays.sort(person, new AgeComparator());
System.out.println("\n\nOrder of person after sorting by person age is");
for(int i=0; i < person.length; i++){
System.out.println( person[i].getName() + "\t" + person[i].getAge());
}
}
}
Output: -
C:\java\word>javac ComparatorExample.java
C:\java\word>java ComparatorExample
Order of person before sorting is
A 35
B 30
C 32
Order of person after sorting by person age is
B 30
C 32
A 35


Free Web Hosting