Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

Friday, 14 April 2017

Sort HashMap in Java based on Values

Using AraryList with Comparator:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class SortByKeyListComp {
     private static void printSortedMap(Map<String, Integer> map) {
           /* Create the entry set. */
           Set<Entry<String, Integer>> set = map.entrySet();
          
           /* Create a list from EntrySet. */
           List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
          
           /* Sort List using the comparator. */
           Collections.sort( list, newComparator<Map.Entry<String, Integer>>() {
                public intcompare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                     return (o2.getValue()).compareTo(o1.getValue() );
                }
           });
          
           /* Print data. */
           for(Map.Entry<String, Integer> entry: list) {
                System.out.println("key#"+entry.getKey()+" value#"+entry.getValue());
           }
     }
    
     /**
      * Driver Method.
      */
     public static void main(String[] args) {
           Map<String, Integer> map = newHashMap<String, Integer>();
           map.put("geeks", 3);
           map.put("nerd", 2);
           map.put("test", 7);
          
           printSortedMap(map);
     }
}


Using TreeMap with Comparator:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


class ValueComparator implements Comparator {
     Map map;

     /* Set Map in Constructor. */
     public ValueComparator(Map map) {
           this.map = map;
     }

     /**
      * Compare the values using the default value of the Map.
      */
     public intcompare(Object keyA, Object keyB) {
           Comparable valueA = (Comparable) map.get(keyA);
           Comparable valueB = (Comparable) map.get(keyB);
           return valueB.compareTo(valueA);
     }
}

public class SortByKeyTreeComp {

     public static Map sortByValue(Map unsortedMap) {
           /* Pass Map to ValueComparator so we can compare on the basic from defualt key.*/
           ValueComparator vc = newValueComparator(unsortedMap);
           Map sortedMap = newTreeMap(vc);
           sortedMap.putAll(unsortedMap);
           return sortedMap;
     }

     public static void main(String[] args) {
           HashMap<String, Integer> map = newHashMap<String, Integer>();
           map.put("geeks", 3);
           map.put("nerd", 2);
           map.put("test", 7);

           System.out.println(map);
           Map sortedMap = sortByValue(map);
           System.out.println(sortedMap);
     }

}

Wednesday, 22 March 2017

Synchronized vs Concurrent Collections

Synchronize means: the resource (which is synchronized) can't be modified by multiple threads simultaneously.

Synchronized and Concurrent Collections can be used to provide thread-safety; however differences between them come in performance, scalability and the way to achieve thread-safety. Synchronized collections (=synchronized HashMap, Hashtable, HashSet, Vector and synchronized ArrayList) are much slower than their concurrent counterparts (=ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet). Because synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping.

Hashtable vs. ConcurrentHashMap
So what is the difference between Hashtable and ConcurrentHashMap, both can be used in multi-threaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration. Since ConcurrentHashMap introduced concept of segmentation, It doesn't matter whether how large it becomes because only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locks certain portion of Map while Hashtable lock full map while doing iteration or performing any write operation.

ArrayList vs. CopyOnWriteArrayList

CopyOnWriteArrayList allows multiple reader threads to read without synchronization and when a write happens it copies the whole ArrayList and swap with a newer one.

Tuesday, 28 February 2017

What is initial capacity and load factor?


Initial capacity is nothing but the number of buckets when the hash table is created, capacity is automatically increased when hash table get full of element.

Load factor is a measurement of how full collection (hash table) is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

How it affects performance?
As a general rule, the default load factor (.75) offers a good trade-off between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

Conclusion:
So finally we can conclude default load capacity (.75) used by Hash Map is a good value in most situations. We can set the initial capacity of Hash Map based on own knowledge of how many items it will hold.

Set it like, initial-capacity = number of items/.75 (round up).


Monday, 27 February 2017

Comparable vs. Comparator

Comparable: java.lang
Comparator: java.util

1) It provides single sorting sequence.

We can sort on particular single scenario.

It provides multiple sorting sequences.

We can provide different comparator to sort.

2) Comparable affects the original class i.e. actual class is modified.

Comparator doesn't affect the original class i.e. actual class is not modified.
3) Comparable provides compareTo() method to sort elements.
Comparator provides compare() method to sort elements.

4) We can sort the list elements of Comparable type by Collections.sort(List) method.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.




package com.comparator;
import java.util.Comparator;
public class StringComparator implements Comparator<String>{

       @Override
       public int compare(String objStr1, String objStr2) {
              int result = 0;
              if(objStr1!=null && objStr2!=null) {
                     result = -1 * objStr1.compareTo(objStr2);
              }
              return result;
       }
}

package com.comparator;
import java.util.Map;
import java.util.TreeMap;
public class TestComparator {
       public static void main(String[] args) {
             
              /**
               * Default Sorting accoding to comparable implemetation of
               * string class in ascending order.
               */
              Map<String,String> map = new TreeMap<String,String>();
              map.put("A""1");
              map.put("B""2");
              map.put("C""3");
             
              System.out.println(map);
             
              /**
               * Using external comparator sort String keys in descending order.
               */
              StringComparator comparator = new StringComparator();
              Map<String,String> compMap = new TreeMap<String,String>(comparator);
              compMap.put("A""1");
              compMap.put("B""2");
              compMap.put("C""3");
             
              System.out.println(compMap);
       }
}

Output:
{A=1, B=2, C=3}
{C=3, B=2, A=1}

Related Posts Plugin for WordPress, Blogger...