Collections

Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method

Example:

import java.util.*;

public class SetDemo {

  public static void main(String args[]) {
     int count[] = {34, 22,10,60,30,22};
     Set<Integer> set = new HashSet<Integer>();
     try{
        for(int i = 0; i<5; i++){
           set.add(count[i]);
        }
        System.out.println(set);
 
        TreeSet sortedSet = new TreeSet<Integer>(set);
        System.out.println("The sorted list is:");
        System.out.println(sortedSet);

        System.out.println("The First element of the set is: "+
                          (Integer)sortedSet.first());
        System.out.println("The last element of the set is: "+
                        (Integer)sortedSet.last());
     }
     catch(Exception e){}
  }
}
This would produce following result:

[34, 30, 60, 10, 22]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method

Example:

import java.util.*;

public class CollectionsDemo {

   public static void main(String[] args) {
      List a1 = new ArrayList();
      a1.add("Zara");
      a1.add("Mahnaz");
      a1.add("Ayan");
      System.out.println(" ArrayList Elements");
      System.out.print("\t" + a1);

      List l1 = new LinkedList();
      l1.add("Zara");
      l1.add("Mahnaz");
      l1.add("Ayan");
      System.out.println();
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + l1);
   }
}
This would produce following result:

ArrayList Elements [Zara, Mahnaz, Ayan]

LinkedList Elements [Zara, Mahnaz, Ayan]


Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys.
  • In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()

Example:

import java.util.*;

public class CollectionsDemo {

   public static void main(String[] args) {
      Map m1 = new HashMap();
      m1.put("Zara", "8");
      m1.put("Mahnaz", "31");
      m1.put("Ayan", "12");
      m1.put("Daisy", "14");
      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);
   }
}
This would produce following result:
Map Elements
{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}


Popular implementation

List - ArrayList, LinkedList and Vector

Set - HashSet, TreeSet and LinkedHashSet

Map - HashMap, Hashtable and TreeMap


When to use List, Set and Map in Java???


Based upon our understanding of difference between Set, List and Map we can now decide when to use List, Set or Map in Java.

1) If you need to access elements frequently by using index, than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know index.

 

2) If you want to store elements and want them to maintain an order on which they are inserted into collection then go for List again, as List is an ordered collection and maintain insertion order.

 

3) If you want to create collection of unique elements and don't want any duplicate than choose any Set implementation e.g. HashSet, LinkedHashSet or TreeSet. All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.

 

4) If you store data in form of key and value than Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need. In order to choose between first two see difference between HashSet and HashMap in Java.


That's all on difference between Set, List and Map in Java. All three are most fundamental interface of Java Collection framework and any Java developer should know there distinguish feature and given a situation should be able to pick right Collection class to use. It's also good to remember difference between there implementation e.g. When to use ArrayList and LinkedList , HashMap vs Hashtable  or When to use Vector or ArrayList etc. Collection API is huge and it's difficult to know every bits and piece but at same time there is no excuse for not knowing fundamentals like Difference between Set, List and Map in Java.


Choosing the right Collection...


Here is a guide for selecting the proper implementation of a Set, List, or Map. It was compiled for Java 1.4. Many additions have been made to the Collections Framework since then (notably the Queue and Deque interfaces, and various items in java.util.concurrent). These later additions have been omitted here, since this briefer summary should suffice for most cases. The best general purpose or 'primary' implementations are likely ArrayList, LinkedHashMap, and LinkedHashSet. They are marked below as " * ". Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting.

Here, "ordering" refers to the order of items returned by an Iterator, and "sorting" refers to sorting items according to Comparable or Comparator.


Principal features of non-primary implementations :
  •     HashMap has slightly better performance than LinkedHashMap, but its iteration order is undefined
  •     HashSet has slightly better performance than LinkedHashSet, but its iteration order is undefined
  •     TreeSet is ordered and sorted, but slow
  •     TreeMap is ordered and sorted, but slow
  •     LinkedList has fast adding to the start of the list, and fast deletion from the interior via iteration

Iteration order for above implementations :

    HashSet - undefined
    HashMap - undefined
    LinkedHashSet - insertion order
    LinkedHashMap - insertion order of keys (by default), or 'access order'
    ArrayList - insertion order
    LinkedList - insertion order
    TreeSet - ascending order, according to Comparable / Comparator
    TreeMap - ascending order of keys, according to Comparable / Comparator

For LinkedHashSet and LinkedHashMap, the re-insertion of an item does not affect insertion order. For LinkedHashMap, 'access order' is from the least recent access to the most recent access. In this context, only calls to get, put, and putAll constitute an access, and only calls to these methods affect access order.

While being used in a Map or Set, these items must not change state (hence, it is recommended that these items be immutable objects):

    keys of a Map
    items in a Set

Sorting requires either that :

    the stored items implement Comparable
    a Comparator for the stored objects be defined

To retain the order of a ResultSet as specified in an ORDER BY clause, insert the records into a List or a LinkedHashMap.

No comments:

Post a Comment