Posts

Showing posts with the label hashmap

Sort a Map by value !!

Sorting a Map by value in Java: 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.Map.Entry; import java.util.Set; public class SortMapByValue { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("z", 2); map.put("q", 0); map.put("p", 5); map.put("s", 8); map.put("o", 0); map.put("r", 9); map.put("v", 8); System.out.println(map); Set<Entry<String, Integer>> entrySet = map.entrySet(); List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet); Collections.sort(lists, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o...

Hashmap capacity, load factor and fail-fast

Capacity :      Capacity is the   N umber of element HashMap can contain.      initial capacity is the capacity at the time the hash table is created        default initial capacity (16)      capacity increased (2 power n) , where n- number of elements load factor : Defines threshold of HashMap. When re-sizing will occur of HashMap. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. default load factor (.75) fail-fast :

What is the difference between hashmap, hashtable and hashset

Hashmap: Hash table implements Map interface Hash table permits null values and the null key HashMap class is equivalent to Hashtable, except that it is unsynchronized and permits nulls It does not guarantee that the order will remain constant over time constant-time performance for the operations (get, put and remove)   Time complexity - O(1) for  get, put and remove                 (Learn About capacity  ,  load factor  and  fail-fast ) It is not synchronized How to make Hashmap Synchronize                  Map m = Collections.synchronizedMap(new HashMap(...)); Exapmle :                    import java.util.*;                    public class HashMapEx{