Collections in java


Click here to download eclipse supported ZIP file




Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.

The collections framework was designed to meet several goals.

  • The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) are highly efficient.

  • The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.

  • Extending and/or adapting a collection had to be easy.

Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

  • Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

  • Implementations, i.e., Classes: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

  • Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

The Collection Interfaces:

The collections framework defines several interfaces. This section provides an overview of each interface:

SN Interfaces with Description
1

The Collection Interface

This enables you to work with groups of objects; it is at the top of the collections hierarchy.

2

The List Interface

This extends Collection and an instance of List stores an ordered collection of elements.

3

The Set

This extends Collection to handle sets, which must contain unique elements

4

The SortedSet

This extends Set to handle sorted sets

5

The Map

This maps unique keys to values.

6

The Map.Entry

This describes an element (a key/value pair) in a map. This is an inner class of Map.

7

The SortedMap

This extends Map so that the keys are maintained in ascending order.

8

The Enumeration

This is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

The Collection Classes:

Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

The standard collection classes are summarized in the following table:

SN Classes with Description
1 AbstractCollection

Implements most of the Collection interface.

2 AbstractList

Extends AbstractCollection and implements most of the List interface.

3 AbstractSequentialList

Extends AbstractList for use by a collection that uses sequential rather than random access of its elements.

4

LinkedList

Implements a linked list by extending AbstractSequentialList.

5

ArrayList

Implements a dynamic array by extending AbstractList.

6 AbstractSet

Extends AbstractCollection and implements most of the Set interface.

7

HashSet

Extends AbstractSet for use with a hash table.

8

LinkedHashSet

Extends HashSet to allow insertion-order iterations.

9

TreeSet

Implements a set stored in a tree. Extends AbstractSet.

10 AbstractMap

Implements most of the Map interface.

11

HashMap

Extends AbstractMap to use a hash table.

12

TreeMap

Extends AbstractMap to use a tree.

13

WeakHashMap

Extends AbstractMap to use a hash table with weak keys.

14

LinkedHashMap

Extends HashMap to allow insertion-order iterations.

15

IdentityHashMap

Extends AbstractMap and uses reference equality when comparing documents.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

The following legacy classes defined by java.util have been discussed in previous tutorial:

SN Classes with Description
1

Vector

This implements a dynamic array. It is similar to ArrayList, but with some differences.

2

Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

3

Dictionary

Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.

4

Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.

5

Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

6

BitSet

A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.

The Collection Algorithms:

The collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the Collections class.

Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All are immutable.

SN Algorithms with Description
1

The Collection Algorithms

Here is a list of all the algorithm implementation.

How to use an Iterator ?

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

SN Iterator Methods with Description
1

Using Java Iterator

Here is a list of all the methods with examples provided by Iterator and ListIterator interfaces.

How to use a Comparator ?

Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means.

This interface lets us sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify).

SN Iterator Methods with Description
1

Using Java Comparator

Here is a list of all the methods with examples provided by Comparator Interface.

Summary:

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.


Hierarchy of Collection Framework

Let us see the hierarchy of collection framework.The java.util package contains all the classes and interfaces for Collection framework.

hierarchy of collection framework

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No.MethodDescription
1public boolean add(Object element) is used to insert an element in this collection.
2public boolean addAll(Collection c)is used to insert the specified collection elements in the invoking collection.
3public boolean remove(Object element)is used to delete an element from this collection.
4public boolean removeAll(Collection c)is used to delete all the elements of specified collection from the invoking collection.
5public boolean retainAll(Collection c)is used to delete all the elements of invoking collection except the specified collection.
6public int size()return the total number of elements in the collection.
7public void clear()removes the total no of element from the collection.
8public boolean contains(Object element)is used to search an element.
9public boolean containsAll(Collection c)is used to search the specified collection in this collection.
10public Iterator iterator()returns an iterator.
11public Object[] toArray()converts collection into array.
12public boolean isEmpty()checks if collection is empty.
13public boolean equals(Object element)matches two collection.
14public int hashCode()returns the hashcode number for collection.

Examples of collection framework :

 

    
package com.cv.java.collection;

import java.util.TreeSet;

/**
 @author Chandra Vardhan
 
 */
public class ComparatorTest {

  public static void main(String[] args) {
    Employee e1 = new Employee("shravya"100);
    Employee e2 = new Employee("chandra"101);
    Employee e3 = new Employee("vardhan"102);
    Employee e4 = new Employee("kodam"103);

    TreeSet<Employee> t1 = new TreeSet<Employee>();
    t1.add(e1);
    t1.add(e2);
    t1.add(e3);
    t1.add(e4);
    System.out.println(t1);
    
    TreeSet<Employee> t2 = new TreeSet<Employee>(new EmployeeComparator());
    t2.add(e1);
    t2.add(e2);
    t2.add(e3);
    t2.add(e4);
    System.out.println(t2);
  }
}


 

    
package com.cv.java.collection;

/**
 @author Chandra Vardhan
 
 */
public class Employee implements Comparable<Employee> {
  private String name;
  private Integer eid;

  Employee(String name, int eid) {
    this.name = name;
    this.eid = eid;

  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getEid() {
    return eid;
  }

  public void setEid(Integer eid) {
    this.eid = eid;
  }

  @Override
  public String toString() {
    return "Employee [name=" + name + ", eid=" + eid + "]";
  }

  @Override
  public int compareTo(Employee obj) {
    return obj.eid.compareTo(this.eid);
  }
}


 

    
package com.cv.java.collection;

import java.util.Comparator;

public class EmployeeComparator implements Comparator<Employee> {

  @Override
  public int compare(Employee o1, Employee o2) {

    return o1.getEid().compareTo(o2.getEid());
  }

}


 

    
package com.cv.java.collection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 @author Chandra Vardhan
 
 */
public class HashMapIteration {

  public static void main(String[] args) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("shravya"100);
    map.put("chandra"200);
    map.put("vardhan"300);
    map.put("kodam"400);

    System.out.println(map);

    Set<String> keys = map.keySet();
    System.out.println(keys);
    Collection<Integer> values = map.values();
    System.out.println(values);
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      System.out.println(entry.getKey() " " + entry.getValue());
    }
  }
}


 

    
package com.cv.java.collection;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 @author Chandra Vardhan
 
 */
public class HashSetExample {

  public static void main(String[] args) {
    Set<String> set = new HashSet<String>();
    set.add("a");
    set.add("B");
    set.add("c");
    set.add("d");
    set.add("null");
    System.out.println(set);
    
    Set<String> linkedHashSet = new LinkedHashSet<String>();
    linkedHashSet.add("a");
    linkedHashSet.add("B");
    linkedHashSet.add("c");
    linkedHashSet.add("d");
    linkedHashSet.add("null");
    System.out.println(linkedHashSet);
  }

}


 

    
package com.cv.java.collection;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.RandomAccess;
import java.util.Vector;

public class InstanceOfOperatorExample {

  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    LinkedList<String> linkedList = new LinkedList<String>();
    Vector<String> vector = new Vector<String>();
    
    System.out.println(arrayList instanceof Serializable);
    System.out.println(arrayList instanceof Cloneable);
    System.out.println(arrayList instanceof RandomAccess);
    
    System.out.println(linkedList instanceof Serializable);
    System.out.println(linkedList instanceof Cloneable);
    System.out.println(linkedList instanceof RandomAccess);
    
    System.out.println(vector instanceof Serializable);
    System.out.println(vector instanceof Cloneable);
    System.out.println(vector instanceof RandomAccess);

  }

}


 

    
package com.cv.java.collection;

import java.util.Comparator;

public class IntegerComparator implements Comparator<Integer> {

  public int compare(Integer o1, Integer o2) {
    String s1 = o1.toString();
    String s2 = o2.toString();
    return s2.compareTo(s1);
  }

}


 

    
package com.cv.java.collection;

import java.util.ArrayList;
import java.util.Iterator;

/**
 @author Chandra Vardhan
 
 */
public class IteratorArrayListExample {

  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>();
    for (int i = 1; i <= 10; i++) {
      al.add(i);
    }
    System.out.println(al);
    Iterator<Integer> itr = al.iterator();
    while (itr.hasNext()) {
      Integer i = (Integeritr.next();
      if (i % == 0)
        System.out.println(i);
      else
        itr.remove();

    }
    System.out.println(al);

  }
}


 

    
package com.cv.java.collection;

import java.util.LinkedList;

/**
 @author Chandra Vardhan
 
 */
public class LinckedListExample {

  public static void main(String[] args) {

    LinkedList<Integer> ll = new LinkedList<Integer>();
    ll.add(10);
    ll.add(20);
    ll.add(30);
    ll.addFirst(40);
    ll.addLast(50);
    // ll.getFirst();
    // ll.getLast();
    System.out.println(ll);
    ll.removeFirst();
    ll.removeLast();
    System.out.println(ll);
  }

}


 

    
package com.cv.java.collection;

import java.util.TreeMap;

//import java.util.TreeSet;

/**
 @author Chandra Vardhan
 
 */
public class NavigationMapExample {

  public static void main(String[] args) {
    TreeMap<String, String> t = new TreeMap<String, String>();
    t.put("a""apple");
    t.put("b""ball");
    t.put("c""cat");
    t.put("d""dog");
    System.out.println(t);
    System.out.println(t.ceilingKey("a"));
    System.out.println(t.descendingMap());
    System.out.println(t.floorKey("b"));
    System.out.println(t.pollFirstEntry());
    System.out.println(t.pollLastEntry());
    System.out.println(t);
    System.out.println(t.descendingMap());

  }
}


 

    
package com.cv.java.collection;

import java.util.PriorityQueue;

/**
 @author Chandra Vardhan
 
 */
public class PriorityQueueExample {

  public static void main(String[] args) {
    PriorityQueue<String> q = new PriorityQueue<String>(15new StringComparator());
    q.offer("shravya");
    q.offer("chandra");
    q.offer("kodam");
    System.out.println(q);

  }
}


 

    
package com.cv.java.collection;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 @author Chandra Vardhan
 
 */
public class PropertiesFileExample {

  public static void main(String[] argsthrows IOException {
    Properties properties = new Properties();
    String fileName = "config.properties";
    File file = new File(fileName).getAbsoluteFile();
    System.out.println(file);
    FileInputStream fis = new FileInputStream(file);
    properties.load(fis);
    System.out.println(properties.setProperty("username", fileName));
    System.out.println(properties.getProperty("password"));
    System.out.println(properties);

  }

}


 

    
package com.cv.java.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

/**
 @author Chandra Vardhan
 
 */
public class ReverseCollectionExample {
  public static void main(String[] args) {
    String[] coins = "A""B""C""D""E" };
        List<String> l = new ArrayList<String>();
        for (int i = 0; i < coins.length; i++)
           l.add(coins[i]);
        ListIterator<String> liter = l.listIterator();
        System.out.println("Before reversal");
        while (liter.hasNext())
           System.out.println(liter.next());
        Collections.reverse(l);
        liter = l.listIterator();
        System.out.println("After reversal");
        while (liter.hasNext())
           System.out.println(liter.next());

  }
}


 

    
package com.cv.java.collection;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class ReverseCollectionExample2 {

  public static void main(String[] args) {
    // create linked list object
    List<Integer> list = new LinkedList<Integer>();

    // populate the list
    list.add(-28);
    list.add(20);
    list.add(-12);
    list.add(8);

    // create comparator for reverse order
    Comparator<Integer> cmp = Collections.reverseOrder();

    // sort the list
    Collections.sort(list, cmp);

    System.out.println("List sorted in ReverseOrder: ");
    for (Object i : list) {
      System.out.println(i + " ");
    }
  }

}


 

    
package com.cv.java.collection;

import java.util.ArrayList;
import java.util.Collections;

public class ReverseCollectionExample3 {
  public static void main(String[] args) {
    // create array list object
    ArrayList<String> arrlst = new ArrayList<String>();

    // populate the list
    arrlst.add("A");
    arrlst.add("B");
    arrlst.add("C");
    arrlst.add("D");
    arrlst.add("E");

    System.out.println("The initial list is :" + arrlst);

    // reverse the list
    Collections.reverse(arrlst);

    System.out.println("The Reverse List is :" + arrlst);
  }
}


 

    
package com.cv.java.collection;

import java.util.Arrays;

/**
 @author Chandra Vardhan
 
 */
public class SearchingConceptUsingArrays {

  public static void main(String[] args) {

    int[] a = 1040705030 };
    Arrays.sort(a);
    System.out.println("before sorting Array:");
    System.out.println(Arrays.binarySearch(a, 10));
    System.out.println(Arrays.binarySearch(a, 50));
    System.out.println(Arrays.binarySearch(a, 80));
//    System.out.println("after sorting array:");
    for (int i : a) {
      System.out.println(i);
    }
    String[] s = "shravya""chandu""kodam""vardhan" };
    Arrays.sort(s);
    for (String string : s) {
      System.out.println(string);
    }
    System.out.println(Arrays.binarySearch(s, "kodam"));
//    System.out.println("searching before array:");

  }

}


 

    
package com.cv.java.collection;

import java.util.ArrayList;
import java.util.Collections;


/**
 @author Chandra Vardhan
 
 */
public class SearchingConceptUsingCollections {

  public static void main(String[] args) {
    ArrayList<Integer> l=new ArrayList<Integer>();
        l.add(100);
        l.add(200);
        l.add(300);
        l.add(400);
        System.out.println(l);
        //Sorting with the IntegerComparator
        Collections.sort(l, new IntegerComparator());
        
        System.out.println(Collections.binarySearch(l,100,new IntegerComparator()));
        System.out.println(Collections.binarySearch(l,200,new IntegerComparator()));
        System.out.println(Collections.binarySearch(l,400));
        
        
        //Sorting normally
        Collections.sort(l);
        
        System.out.println(Collections.binarySearch(l,100,new IntegerComparator()));
        System.out.println(Collections.binarySearch(l,200));
        System.out.println(Collections.binarySearch(l,400));
  }

}


 

    
package com.cv.java.collection;

import java.util.Arrays;

/**
 @author Chandra Vardhan
 
 */
public class SortingConceptUsingArrays {
  public static void main(String[] args) {
    int[] a = 5107202522 };
    System.out.println("primitive before sorting :");
    for (int a1 : a) {
      System.out.print(a1 + " ");
    }
    System.out.println();
    Arrays.sort(a);
    System.out.println("primitive after sorting:");
    for (int s1 : a) {
      System.out.print(s1 + " ");
    }
    System.out.println();
    String[] s = "a""c""b""z""x" };
    System.out.println("String before sorting:");
    for (String s2 : s) {
      System.out.print(s2 + " ");
    }
    System.out.println();
    Arrays.sort(s);
    System.out.println("String after sorting:");
    for (String s3 : s) {
      System.out.print(s3 + " ");
    }
    System.out.println();
  }
}


 

    
package com.cv.java.collection;

import java.util.ArrayList;
import java.util.Collections;

/**
 @author Chandra Vardhan
 
 */
public class SortingConceptUsingCollections {

  public static void main(String[] args) {
    ArrayList<String> al = new ArrayList<String>();
    al.add("A");
    al.add("K");
    al.add("C");
    al.add("z");
    System.out.println("before sorting:" + al);
    Collections.sort(al);
    System.out.println("after sorting:" + al);
    ArrayList<String> al2 = new ArrayList<String>();
    al2.add("A");
    al2.add("K");
    al2.add("C");
    al2.add("z");
    System.out.println("===================");
    System.out.println("before sorting:" + al2);
    Collections.sort(al2, new StringComparator());
    System.out.println("after sorting:" + al2);

  }

}


 

    
package com.cv.java.collection;

import java.util.Stack;

/**
 @author Chandra Vardhan
 
 */
public class StackExample {

  public static void main(String[] args) {
    Stack<String> s = new Stack<String>();
    s.push("A");
    s.push("B");
    s.push("C");
    s.push("D");
    s.pop();
    s.pop();
    System.out.println(s.peek());
    System.out.println(s.peek());
    System.out.println(s.peek());
    System.out.println(s);
    System.out.println(s.search("A"));
    System.out.println(s.empty());

  }

}


 

    
package com.cv.java.collection;

import java.util.Comparator;

public class StringComparator implements Comparator<String> {

  public int compare(String o1, String o2) {
    return o2.compareTo(o1);
  }

}


 

    
package com.cv.java.collection;

import java.util.Set;
import java.util.TreeSet;


/**
 @author Chandra Vardhan
 
 */
public class TreeSetExample {
  
  public static void main(String[] args) {
    Set<Integer> set = new TreeSet<Integer>();
    set.add(10);
    set.add(20);
    set.add(30);
    set.add(40);
    set.add(50);
    set.add(60);
    System.out.println(set);  
    
    Set<Integer> treeSet = new TreeSet<Integer>(new IntegerComparator());
    treeSet.add(10);
    treeSet.add(20);
    treeSet.add(30);
    treeSet.add(40);
    treeSet.add(50);
    treeSet.add(60);
    System.out.println(treeSet);
  }
}


 

    
package com.cv.java.collection;

import java.util.Enumeration;
import java.util.Vector;

/**
 @author Chandra Vardhan
 
 */
public class VectorEnumerationExample {

  public static void main(String[] args) {
    Vector<Integer> v = new Vector<Integer>();
    for (int i = 0; i < 10; i++) {
      v.add(i);
      System.out.print(i + " ");
    }
    System.out.println();
    Enumeration<Integer> e = v.elements();
    while (e.hasMoreElements()) {
      Integer i = (Integere.nextElement();
      if (i % == 0) {
        System.out.println(i);
      }
    }

  }
}

No comments:

Post a Comment