Tuesday, January 28, 2014

Working with Java Collections- Collections and Arrays Classes

Collections and Arrays are two utility classes to work with the Java Collections.These classes are used for sorting ,searching and working with customized collections .To compare the elements the List object should be comparable.Shown below introduce some of the useful method of Collections class



package collections;

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

public class WorkingWithCollections {
       public static void main(String[] args) {

              ArrayList<String> aList = new ArrayList<String>();
              aList.add("Raj");
              aList.add("Sun");
              aList.add("Tol");
              aList.add("Jap");

              Collections.sort(aList);
              System.out.println("Sort : " + aList);

              Collections.sort(aList, Collections.reverseOrder());

              Collections.sort(aList, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));

              System.out.println(aList);

              Collections.reverse(aList);
              System.out.println(aList);

              Collections.rotate(aList, 3);
              System.out.println(aList);

              Collections.shuffle(aList);
              System.out.println(aList);

              Collections.swap(aList, 2, 3);
              System.out.println("Swap : " + aList);

              ArrayList<Emp> empList = new ArrayList<Emp>();

              Emp e1 = new WorkingWithCollections().new Emp();
              e1.setId(1);
              e1.setName("Raj");
              empList.add(e1);

              e1 = new WorkingWithCollections().new Emp();
              e1.setId(2);
              e1.setName("Sun");
              empList.add(e1);

              e1 = new WorkingWithCollections().new Emp();
              e1.setId(3);
              e1.setName("Jap");
              empList.add(e1);

              Collections.sort(empList, new WorkingWithCollections().new EmpComparator());
              System.out.println(empList);
              for (Emp e : empList) {
                     System.out.println(e.getName());
              }

       }

       public class Emp implements Comparable {
              private int id;
              private String name;

              public int getId() {
                     return id;
              }

              public void setId(int id) {
                     this.id = id;
              }

              public String getName() {
                     return name;
              }

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

              @Override
              public int compareTo(Object o) {
                     // TODO Auto-generated method stub
                     return 0;
              }

       }

       public class EmpComparator implements Comparator {

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

                     String s1 = ((Emp) o1).getName();
                     String s2 = ((Emp) o2).getName();

                     return s1.compareTo(s2);
              }

       }
}

Arrays

Searching in Arrays the array needs to sort naturally.Arrays provide set of List views method.asList() in arrays and toArray() in List act as a bridge between collections and arrays.List return from asList() cannot be changed 

package collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class WorkingWithArrays {

    public static void main(String[] args) {

        String a[] = { "Jan", "Feb", "Mar", "Apr", "May" };
        Arrays.sort(a);
        for (String str : a) {
            System.out.println(str);
        }
        System.out.println("Search : " + Arrays.binarySearch(a, "Mar"));
        System.out.println("Search1 : " + Arrays.binarySearch(a, "Mar", String.CASE_INSENSITIVE_ORDER));

        System.out.println("Search1 : " + Arrays.binarySearch(a, "Mar", Collections.reverseOrder()));// Search wont work
                                                                                                        // here.

        Arrays.sort(a, Collections.reverseOrder());
        for (String str : a) {
            System.out.println(str);
        }

        System.out.println(Arrays.asList(a));// Array of primitive type cannot pass to this method

        // Avoid duplicates

        ArrayList<String> dList = new ArrayList<String>();
        dList.add("Sun");
        dList.add("Amay");
        dList.add("Amay");
        dList.add("Tar");

        Object oa[] = dList.toArray();
        Arrays.deepToString(oa);

        System.out.println(oa);
        Set<String> s = new HashSet<String>(dList);
        System.out.println("Deep to str :" + Arrays.toString(oa));

        System.out.println(Arrays.toString(a));
        Arrays.fill(a, "TTT");
        System.out.println(Arrays.toString(a));

    }

}
 
 

Java Collection :Map Interface

Map is used to map between keys and values. Key, Value pair is called Entry.Map doesn't allow duplicate keys.Keys and Values must be objects. No primitive types are allowed.Map is not a collection.Mapping can be viewed as collections by keySet, a value collection and EntrySet



package collections;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class MapTest {
       public static void main(String[] args) {

              // Basic Operations
              HashMap<String, String> m = new HashMap<String, String>();
              m.put("key1", "Value1");
              m.put("key2", "Value2");
              m.put("key3", "Value3");
              m.put("key4", "Value3");

              System.out.println(m.get("key1"));

              m.remove("key1");
              System.out.println(m);

              System.out.println(m.containsKey("key4"));
              System.out.println(m.containsValue("Value3"));
              System.out.println(m.size());
              System.out.println(m.isEmpty());

              // Bulk Operations

              Map<String, String> m1 = new HashMap<String, String>();
              m1.putAll(m);
              System.out.println(m);
              System.out.println(m1);

              m1.clear();
              System.out.println(m1);

              // Collections views
              System.out.println(m.keySet());
              System.out.println(m.values());
              System.out.println(m.entrySet());
              Iterator<Entry<String, String>> itr = m.entrySet().iterator();
              while (itr.hasNext()) {
                     Entry<String, String> e = itr.next();
                     System.out.println(e.getKey() + " : " + e.getValue());
              }
       }
}


Map Implementations

HashMap,LinkedHashMap and Hashtable classes are using Map ineterface. HashMap and HashTable are unordered maps.LinkedHashMap is an ordered map. TreeMap is a sorted map.HashMap allows one null value as key . Hashtable is threadsafe and doesn't allow null values. Hashtable's threadsafe features comes with a performance penalty for synchronization.Map implementation is based on hashing algorithms.It relay on hashcode() and equals() implementation.LinkedHashMap is subclass of HashMap.LinkedHashMap's ordering is by default is key insertion order.LinkedHashMap also maintains keys in access order. Ordering mode can be specified in the constructor. Adding removing and searching of LinkedHashMap is slightly slower than HashMap.Traversal of HashMap is through Collection views.



package collections;

import java.util.LinkedHashMap;

public class MapImplTest {
       public static void main(String[] args) {

              // Constructors
              LinkedHashMap<String, String> lm = new LinkedHashMap<String, String>();
              LinkedHashMap<String, String> lm1 = new LinkedHashMap<String, String>(10);// with initial capaity
              LinkedHashMap<String, String> lm2 = new LinkedHashMap<String, String>(10, 1);// initial capacity and loadfactor
              LinkedHashMap<String, String> lm3 = new LinkedHashMap<String, String>(10, 1, true);// With access order . Key
                                                                                                                                                              // insertion order 3rd param
                                                                                                                                                              // =false

              System.out.println(lm + " " + lm1 + " " + lm2 + " " + lm3);
       }

}

SortedMap<K,V> and NavigableMap<K,V> Interfaces

SortedMap<K,V>
SortedMap extends Map interface . SortedMaps are maps with sorted keys

NavigableMap<K,V>

NavigableMap extends SortedMap.NavigableMap is prefrerred choice thanSortedMap.

TreeMap Class

TreeMap is sorted Map.TreeMap implements Navigable map and there by sorted.TreeMap has by default natural ordering but Comparators are supported.TreeMap provides balanced trees and provides excellent performance.Searching HashMap is faster than TreeMap as the hashing algorithm provides better performance than TreeBased algorithm.

package collections;

import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapTest {
    public static void main(String[] args) {

        HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("ke1", "Value1");
        hm.put("ke2", "Value2");
        hm.put("ke3", "Value3");
        hm.put("ke4", "Value4");
        hm.put("ke5", "Value5");

        SortedMap<String, String> m = new TreeMap<String, String>(hm);
        System.out.println(m);
        System.out.println(m.firstKey()); // Set is empty NoSuchEmenetException
        System.out.println(m.lastKey());

        System.out.println(m.headMap("ke3"));// toKey
        System.out.println(m.tailMap("ke3"));// formKey

        System.out.println(m.comparator());// Null if no comparator

        NavigableMap<String, String> nm = new TreeMap<String, String>(hm);

        System.out.println(nm);

        Map.Entry<String, String> me1 = nm.firstEntry();
        System.out.println(me1.getKey() + " : " + me1.getValue());

        Map.Entry<String, String> me2 = nm.lastEntry();
        System.out.println(me2.getKey() + " : " + me2.getValue());

        System.out.println(nm);

        nm.pollFirstEntry();// remove first entry
        nm.pollLastEntry();// remove last entry

        System.out.println(nm);

        nm = new TreeMap<String, String>(hm);
        System.out.println(nm);

        System.out.println(nm.headMap("ke3", true));// toElement,inclusive
        System.out.println(nm.headMap("ke3", false));

        System.out.println(nm.tailMap("ke3", true));// fromElement,inclusive

        System.out.println(nm.subMap("ke2", true, "ke4", false));// toElement,inclusive,fromElement,inclusive

        // Closest Match

        Map.Entry<String, String> ce = nm.ceilingEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.floorEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.higherEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.lowerEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        System.out.println(nm.descendingMap()); // Descending map
        System.out.println(nm.descendingKeySet());// Descending keys
        System.out.println(nm.navigableKeySet());// forward order keys
    }

}