Wednesday, 22 July 2015

Java Collections









What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
  1. Collection extends Iterable
  2. An iterator is an object that enables t traverse through a collection and to remove elements from the collection selectively, if required.
  3. Set
  • Set is a Collection that cannot contain duplicate elements.
  • Set interface contains only methods from Collection.
  • Two Set instances are equal if they have same elements.
  • There are three Set implementations
      HashSet
  • Stores the elements in a hash table
  • Uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • Contains unique elements only.
      TreeSet – orders the elements based on their values

       List<String> li = new ArrayList<String>();
       TreeSet<String> myset = new TreeSet<String>(li);


  • Removing duplicates from array.

               String[] strArr = {"one","two","three","four","four","five"};
               List<String> tmpList = Arrays.asList(strArr);

               TreeSet<String> unique = new TreeSet<String>(tmpList);

      LinkedHashSet – orders the elements based on the order in which it is inserted
  • Bulk operations:
              If s1 and s2 are two sets:
              s1. containsAll(s2) – returns true if s2 is a subset of s1
              s1.addAll(s1) – transforms s1 into the union of s1 and s2
              s1.retainAll(s2) – transforms s1 into the intersection of s1 and s2
              s1.removeAll(s2) – transforms s1 into the set difference of s1 and s24


  1. Arrays,Collections are utility class available in java.util package.

No comments:

Post a Comment