Wednesday, July 8, 2015

Collections in Java



Java SE : Collections 

There are lot of scenarios where Collections are helpful.
The Java collections are nothing but a set of classes and interfaces that implement commonly reusable collection data structures like Arrays, lists, sets, queues, stacks and dictionaries. And there is one more type that is map which is not implements Collection interface but come under Collections framework.
Along with the collections classes there are several other classes and interfaces which are part of Collection Framework used to manipulated the collection data.
Below I’m listing the scenarios where we need to use collection classes.
  1. Fetch data from database and store each record into suitable collection class.
  2. Hold the data and transfer the data from UI to database and vice versa.
  3. Sorting the entity objects for example sorting of Employee object based on the Emp_Id or Emp_Name etc. (Assume Employee class have properties Emp_Id and Emp_Name.)
  4. Removing of the duplicate data (String or Objects) by using sets.
  5. Search the data in the collections class
  6. Storing the objects in key value pair.
There are so many scenarios where we can use collections. The listed are primary one.

I am not going tell you what is collection but I am going give some real time usage of collections as cited below
  1. suppose in your project you got a requirement like you have to sort the employee based on seniority and show the result ,now you have already list of employee with you,sort that list based on age property of employee ,in this case use collections.sort().in this case you are avoiding making any DB call.so this will give you faster result.
  2. map collection being used to create in memory cache.suppose in your project you got requirement like first 100 records need show based on the default selection whenever user login in the system.In this case use map to store the 100 records in cache when your application gets up.with this you will give user good experience about usage of your application.
I hope this will help to clarify your doubt.

What is Collections Framework in Java?
  • A single unit of objects.
  • It's a framework.
  • It provides an architecture to store and manipulate the cluster of objects.
  • Operations that can be performed are searching, sorting, insertion, manipulation, deletion and etc.
  • It provides many interfaces like Set, List, Queue, Deque, and etc.
  • The implemented classes are ArrayList, LinkedList, Vector, HashSet, and etc.
Benefits of Collections Framework:
  • Reduces programming effort
  • Increases program speed and quality
  • Allows interoperability among unrelated APIs
  • Reduces effort to learn and to use new APIs
  • Reduces effort to design new APIs
  • Fosters software reuse
Java Collection Interface Methods:
Method
Description
public boolean add(Object element)
It adds the specified element to the invoking collection.
public boolean remove(Object element)
It removes the specified element from the invoking collection.
public int size()
It returns the total elements present in the invoking collection.
public void clear()
It removes all the elements from the invoking collection.
public boolean contains(Object element)
It returns true if the specified element is present in the invoking collection.
public boolean isEmpty()
It returns true if the invoking collection has no elements.

What is an Iterator?
  • An iterator over a collection
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Iterator Interface:
  • Iterator Interface is a member of Java Collections Framework.
  • boolean hashNext() - Returns true if it has more elements
  • E next() - Returns the next element in the iteration
  • void remove() - Removes the last element returned by the iterator.  


  • What is List Interface in Java?
  • A List is an ordered Collection
  • Lists may contain duplicate elements
  • Positional Access - Manipulates elements based on their numerical position in the list
  • Search - Searches for a specified object in the list and returns its index position
Java List interface methods:
Method
Description
void add(int index, Object targetElement)
It inserts the targetElement at the specified position.
boolean addAll(int index, Collection c)
It inserts all the elements that are present in the collection from the specified index position
object get(int index)
It returns the element present at that position
object remove(int index)
It removes the elements that is present at the specified index
Java ArrayList Properties:
  • It cannot contain duplicate values.
  • It maintains insertion order.
  • It is non-synchronized.
  • Manipulation is slow because shifting operation is costlier.
Java ArrayList Constructors:
Constructor
Description
ArrayList()
It is the default constructor and creates an empty list object.
ArrayList(Collection collection)
It creates the list object using the elements of the specified collection.
ArrayList(int capacity)
It creates a list object using the initial capacity.
Java ArrayList Methods:
Method
Description
void add(int index, Object targetElement)
It inserts the targetElement at the specified position.
boolean addAll(int index, Collection c)
It inserts all the elements that are present in the collection from the specified index position
void clear()
It removes all the elements from the invoking list object.
boolean add(Object targetElement)
It appends the targetElement to the invoking list object.
int indexOf(Object targetObject)
It returns the index of the first occurrence of the targetObject.
Java ArrayList Example:
  1. public class ArrayListExample
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6. ArrayList books = new ArrayList<>();
  7. System.out.println("Books size "+books.size());
  8. books.add("C"); // C
  9. books.add("C++"); // C C++
  10. books.add("Java"); // C C++ Java
  11. System.out.println("Books size "+books.size());
  12. System.out.println(books.toString());
  13. // C[0] C++[1] Java[2] existing
  14. books.add(1, "Python"); //C[0] Python[1] C++[2] Java[3] New
  15. System.out.println(books.toString());
  16. //C[0] Python[1] C++[2] Java[3] Existing
  17. System.out.println("Removing C book");
  18. books.remove("C");
  19. //Python[0] C++[1] Java[2] New
  20. System.out.println("Books after removing C ="+books.toString());
  21. }
  22.  
  23. }
  24.  
  25.  
Output:
  1. Books size 0
  2. Books size 3
  3. [C, C++, Java]
  4. [C, Python, C++, Java]
  5. Removing C book
  6. Books after removing C =[Python, C++, Java]
Java LinkedList Properties:
  • It can contain duplicate values.
  • It maintains insertion order.
  • It is not synchronized.
  • Manipulation is fast because no shifting is required.
Java LinkedList Constructors:
Constructor
Description
LinkedList()
It creates an empty list.
LinkedList(Collection collection)
It creates an object using the elements from the collection.
Java LinkedList Methods:
Method
Description
void add(int index, Object element)
It inserts the specified element at the specified position.
void addFirst(Object o)
It inserts the given element at the beginning
void addLast(Object o)
It appends the element at last.
int size()
It returns the size of the list.
boolean add(Object o)
It adds an object at the end of the list.
boolean contains(Object o)
It returns true if the specified object is present in the list.
boolean remove(Object o)
It removes the first occurrence of the specified element.
Object getFirst()
It returns the first occurrence of the specified element.
Object getLast()
It returns the last occurrence of the specified element.
int indexOf(Object o)
It returns the index position of the first occurrence of the specified element.
int lastIndexOf(Object o
It returns the index position of the last occurrence of the specified element
Java LinkedList Example:
  1. public class LinkedListExample
  2. {
  3.  
  4. /*
  5. 1. doubly-linked list data structure
  6. 2. LinkedList is used for adding and removing at the end
  7. Difference between ArrayList and LinkedList
  8. ArrayList
  9. 1. ArrayList internally uses dynamic array to store the elements.
  10. 2. Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
  11. 3. ArrayList is better for storing and accessing data.
  12. LinkedList
  13. 1. LinkedList internally uses doubly linked list to store the elements.
  14. 2. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
  15. 3. LinkedList is better for manipulating data.
  16. */
  17.  
  18. public static void main(String[] args)
  19. {
  20. LinkedList books = new LinkedList<>();
  21.  
  22. System.out.println("Books size " + books.size());
  23.  
  24. books.add("C"); // C
  25. books.add("C++"); // C C++
  26. books.add("Java"); // C C++ Java
  27.  
  28. System.out.println("Books size " + books.size());
  29.  
  30. System.out.println(books.toString());
  31.  
  32. // C[0] C++[1] Java[2] existing
  33. books.add(1, "Python"); //C[0] Python[1] C++[2] Java[3] New
  34.  
  35. System.out.println(books.toString());
  36.  
  37. //C[0] Python[1] C++[2] Java[3] Existing
  38. System.out.println("Removing C book");
  39. books.remove("C");
  40. //Python[0] C++[1] Java[2] New
  41.  
  42. System.out.println("Books after removing C =" + books.toString());
  43. }
  44. }
  45.  
  46.  
Output:
  1. Books size 0
  2. Books size 3
  3. [C, C++, Java]
  4. [C, Python, C++, Java]
  5. Removing C book
  6. Books after removing C =[Python, C++, Java]
  7.  

ArrayList vs LinkedList:
ArrayList
LinkedList
It uses a dynamic array to store the elements.
It uses a doubly linked list to store the elements.
Manipulation is slow because shifting operation is costlier.
Manipulation is fast because there is no shifting operation is involved.
It is better for storing and accessing the data.
It is better for manipulating the data.
It acts as a list.
It acts as a list and queue.

What is a Java Set?
  • Set is a Collection that cannot contain duplicate elements
Set Interface Methods:
Method
Description
boolean add(E e)
It adds the specified element "e" to the set.
void clear()
It removes all the elements from the set.
boolean contains(Object o)
It returns true if the specified object is present else it returns false.
boolean isEmpty()
It returns true if the set has no elements.
boolean remove(Object o)
It returns the specified object from the set.
int size()
It returns the number of elements in the set
Java HashSet Properties:
  • It stores the elements using hashing mechanism.
  • It contains unique elements only.
  • It uses Hash Table for storage.
  • It extends AbstractSet class.
  • It implements Set Interface.
HashSet constructors:
Constructor
Description
HashSet()
It is the default constructor and created an empty object.
HashSet(Collection c)
It creates an object using the elements of the collection c
HashSet(int capacity)
It creates an object with the initial capacity.
HashSet Methods:
Method
Description
boolean add(Object targetObject)
It adds the targetObject in the set.
void clear()
It removes all the elements from the set.
Object clone()
It copies all the elements from the existing object and creates a new set object.
boolean isEmpty()
It returns if the set doesn't contain any elements.
boolean remove(Object o)
It removes the specified object from the set.
int size()
It returns the total elements count of the set.
HashSet Example:
  1. public class HashSetExample
  2. {
  3. /*
  4. 1. HashSet implements Set, exetends AbstractSet
  5. 2. HashSet doesn't maintain order
  6. 3. HashSet stores the elements by using a mechanism called hashing.
  7. 4. HashSet contains unique elements only.
  8. 5. List can contain duplicate elements whereas Set contains unique elements only.
  9. */
  10. public static void main(String[] args)
  11. {
  12. HashSet hashSet=new HashSet<>();
  13. hashSet.add("Rakesh");
  14. hashSet.add("Lenin");
  15. hashSet.add("Rakesh");
  16. hashSet.add("Raja");
  17. System.out.println(hashSet);
  18. //2. contains()
  19. if(hashSet.contains("rakesh"))
  20. {
  21. System.out.println("rakesh is present in hashset");
  22. }
  23. else
  24. {
  25. System.out.println("rakesh is not present in hashset");
  26. }
  27. //3. isEmpty()
  28. if(hashSet.isEmpty())
  29. {
  30. System.out.println("set is empty");
  31. }
  32. else
  33. {
  34. System.out.println("set is not empty");
  35. }
  36. System.out.println("");
  37. System.out.println("values are displayed using iterator");
  38. //4. iterator
  39. Iterator iterator=hashSet.iterator();
  40. while(iterator.hasNext())
  41. {
  42. String value=iterator.next();
  43. System.out.println(value);
  44. }
  45. System.out.println("");
  46. //5. size
  47. System.out.println(hashSet.size());
  48. //6. remove
  49. System.out.println(hashSet.remove("Rakesh"));
  50. System.out.println(hashSet);
  51. }
  52. }
  53.  
  54.  
Output:
  1. [Raja, Lenin, Rakesh]
  2. rakesh is not present in hashset
  3. set is not empty
  4.  
  5. values are displayed using iterator
  6. Raja
  7. Lenin
  8. Rakesh
  9.  
  10. 3
  11. true
  12. [Raja, Lenin]
  13.  

Java LinkedHashSet Properties:
  • It contains only unique elements.
  • It maintains insertion order.
  • It implements Set interface.
  • It extends HashSet class.
Java LinkedHashSet Constructors:
Constructor
Description
LinkedHashSet()
It is the default constructor and creates an empty object.
LinkedHashSet(Collection c)
It creates an object using the elements of the collection c
LinkedHashSet(int capacity)
It creates an object with the initial capacity.
LinkedHashSet(int capacity, int fillRatio)
It creates an object by initialize the initial capacity and fill ratio.
Java LinkedHashSet Methods:
Method
Description
boolean add(Object targetObject)
It adds the targetObject in the set.
void clear()
It removes all the elements from the set.
Object clone()
It copies all the elements from the existing object and creates a new set object.
boolean isEmpty()
It returns if the set doesn't contain any elements.
boolean remove(Object o)
It removes the specified object from the set.
int size()
It returns the total elements count of the set.
Java LinkedHashSet Example:
  1. public class LinkedHashSetExample
  2. {
  3. /*
  4. 1. HashSet doesn't maintain order but LinkedHashSet maintains the insertion order
  5. */
  6. public static void main(String[] args)
  7. {
  8. LinkedHashSet linkedHashSet=new LinkedHashSet<>();
  9. linkedHashSet.add("Rakesh");
  10. linkedHashSet.add("Lenin");
  11. linkedHashSet.add("Rakesh");
  12. linkedHashSet.add("Raja");
  13. System.out.println(linkedHashSet);
  14. //2. contains()
  15. if(linkedHashSet.contains("rakesh"))
  16. {
  17. System.out.println("rakesh is present in hashset");
  18. }
  19. else
  20. {
  21. System.out.println("rakesh is not present in hashset");
  22. }
  23. //3. isEmpty()
  24. if(linkedHashSet.isEmpty())
  25. {
  26. System.out.println("set is empty");
  27. }
  28. else
  29. {
  30. System.out.println("set is not empty");
  31. }
  32. System.out.println("");
  33. System.out.println("values are displayed using iterator");
  34. //4. iterator
  35. Iterator iterator=linkedHashSet.iterator();
  36. while(iterator.hasNext())
  37. {
  38. String value=iterator.next();
  39. System.out.println(value);
  40. }
  41. System.out.println("");
  42. //5. size
  43. System.out.println(linkedHashSet.size());
  44. //6. remove
  45. System.out.println(linkedHashSet.remove("rakesh"));
  46. System.out.println(linkedHashSet);
  47. }
  48. }
  49.  
  50.  
Output:
  1. [Rakesh, Lenin, Raja]
  2. rakesh is not present in hashset
  3. set is not empty
  4.  
  5. values are displayed using iterator
  6. Rakesh
  7. Lenin
  8. Raja
  9.  
  10. 3
  11. false
  12. [Rakesh, Lenin, Raja]
  13.  

Java TreeSet Properties:
  • Implements the Set interface
  • Uses a tree for storage
  • Contains unique elements
  • Maintains ascending order
TreeSet constructors:
Constructor
Description
TreeSet()
It is the default constructor and creates an empty object and applies default sorting.
TreeSet(Collection c)
It creates an object using the elements of the collection c
TreeSet(Comparator comparator)
It creates an object and applying sorting based on the comparator implementation.
TreeSet(SortedSet sortedSet)
It creates a set using the elements from the sortedSet.
Java TreeSet Methods:
Method
Description
boolean add(Object targetObject)
It adds the targetObject in the set.
void clear()
It removes all the elements from the set.
Object clone()
It copies all the elements from the existing object and creates a new set object.
boolean isEmpty()
It returns if the set doesn't contain any elements.
boolean remove(Object o)
It removes the specified object from the set.
int size()
It returns the total elements count of the set.
Java TreeSet Example:
  1. public class TreeSetExample
  2. {
  3. /*
  4. 1. TreeSet maintains ascending order.
  5. */
  6. public static void main(String[] args)
  7. {
  8. TreeSet treeSet=new TreeSet<>();
  9. treeSet.add("Rakesh");
  10. treeSet.add("Lenin");
  11. treeSet.add("Rakesh");
  12. treeSet.add("Raja");
  13. System.out.println(treeSet);
  14. //2. contains()
  15. if(treeSet.contains("rakesh"))
  16. {
  17. System.out.println("rakesh is present in hashset");
  18. }
  19. else
  20. {
  21. System.out.println("rakesh is not present in hashset");
  22. }
  23. //3. isEmpty()
  24. if(treeSet.isEmpty())
  25. {
  26. System.out.println("set is empty");
  27. }
  28. else
  29. {
  30. System.out.println("set is not empty");
  31. }
  32. System.out.println("");
  33. System.out.println("values are displayed using iterator");
  34. //4. iterator
  35. Iterator iterator=treeSet.iterator();
  36. while(iterator.hasNext())
  37. {
  38. String value=iterator.next();
  39. System.out.println(value);
  40. }
  41. System.out.println("");
  42. //5. size
  43. System.out.println(treeSet.size());
  44. //6. remove
  45. System.out.println(treeSet.remove("rakesh"));
  46. System.out.println(treeSet);
  47. }
  48. }
  49.  
Output:
  1. [Lenin, Raja, Rakesh]
  2. rakesh is not present in hashset
  3. set is not empty
  4.  
  5. values are displayed using iterator
  6. Lenin
  7. Raja
  8. Rakesh
  9.  
  10. 3
  11. false
  12. [Lenin, Raja, Rakesh]
  13.  

Comparison among HashSet, LinkedHashSet, and TreeSet in Java
HashSet
LinkedHashSet
TreeSet
It doesn't maintain any order.
It maintains insertion order.
It maintains sorted order. Default sorting is ascending order.
Retrieval is fast.
Retrieval is medium.
Retrieval is slow. 
What is a Map?
  • A map contains values on the basis of key
  • Each key and value pair is known as an entry
  • A map contains only unique keys
Map Interface methods in Java:
Method
Description
Object put(Object key, Object targetObject)
It inserts the targetObject at the specified position(key).
void putAll(Map sourceMap)
It copies all the key/value pairs from the sourceMap to the targetMap.
Object remove(Object key)
It removes the element at the specified position(key).
Object get(Object key)
It returns the value at the specified position(key).
boolean containsKey(Object key)
It returns true if the specified key is present else it returns false.
int size()
It returns the total key/value pairs count of the map. 
Java HashMap Properties:
  • It implements the map interface.
  • It extends AbstractMap class.
  • HashMap contains values based on the key
  • Contains only unique elements
  • May have one null key and multiple null values
  • Maintains no order
Java HashMap Constructors:
Constructor
Description
HashMap()
It is the default constructor. It creates an empty HashMap object.
HashMap(Map existingMap)
It creates a HashMap object bu using the key/value pairs present from the existingMap.
HashMap(Integer capacity)
It creates a HashMap object using the initial capacity.
HashMap(Integer capacity, Integer fillratio)
It creates a HashMap object using the initial capacity and fill ratio.
Java HashMap Methods:
Method
Description
void clear()
It removes all the key/value pairs from the target map.
boolean containsKey(Object targetKey)
It returns true if the targetKey is present in the map else false.
boolean containsValue(Object targetValue)
It returns true if the targeValue is present in the map else false.
boolean isEmpty()
It returns true if the map doesn't contain any key/value pairs
int size()
It returns the total key/value pairs count.
Java HashMap Example:
  1. public class HashMapExample
  2. {
  3.  
  4. /*
  5. 1. HashMap implements map, extends AbstractMap
  6. 2. HashMap contains values based on the key.
  7. 3. contains only unique keys.
  8. 4. have one null key and multiple null values.
  9. 5. maintains no order
  10. */
  11. public static void main(String[] args)
  12. {
  13. HashMap hashMap = new HashMap<>();
  14. //insert key and values
  15. hashMap.put(1, "Rakesh");
  16. hashMap.put(2, "Raja");
  17. hashMap.put(3, "Lenin");
  18. hashMap.put(4, "Chenchu");
  19.  
  20. System.out.println(hashMap);
  21.  
  22. //get the value for the key
  23. System.out.println("getting the value at key 2");
  24. System.out.println(hashMap.get(2));
  25.  
  26. //remove the value at key 2
  27. System.out.println("removing the value for key 2");
  28. hashMap.remove(2);
  29.  
  30. Iterator iterator = hashMap.entrySet().iterator();
  31. while (iterator.hasNext())
  32. {
  33. Map.Entry entry = (Map.Entry) iterator.next();
  34. Integer key = entry.getKey();
  35. String value = entry.getValue();
  36. System.out.println("Key " + key + " value " + value);
  37. }
  38. }
  39. }
Output:
  1. {1=Rakesh, 2=Raja, 3=Lenin, 4=Chenchu}
  2. getting the value at key 2
  3. Raja
  4. removing the value for key 2
  5. Key 1 value Rakesh
  6. Key 3 value Lenin
  7. Key 4 value Chenchu
Java LinkedHashMap Properties:
Java LinkedHashMap Constructors:
Constructor
Description
LinkedHashMap()
It is the default constructor and created an empty object.
LinkedHashMap(int capacity)
It creates an object with the specified capacity.
LinkedHashMap(int capacity, int fillRatio)
It creates an object with the specified capacity and fillRatio.
LinkedHashMap(Map existingMap)
It creates an object using the key/value pairs from the existingMap.
Java LinkedHashMap Methods:
Method
Description
void clear()
It removes all the key/value pairs from the target map.
boolean containsKey(Object targetKey)
It returns true if the targetKey is present in the map else false.
boolean containsValue(Object targetValue)
It returns true if the targeValue is present in the map else false.
boolean isEmpty()
It returns true if the map doesn't contain any key/value pairs
int size()
It returns the total key/value pairs count.
Java LinkedHashMap Example:
  1. public class LinkedHashMapExample
  2. {
  3. /*
  4. maintains order of insertion based on key
  5. */
  6. public static void main(String[] args)
  7. {
  8. LinkedHashMap linkedHashMap = new LinkedHashMap<>();
  9. //insert key and values
  10. linkedHashMap.put(4, "Chenchu");
  11. linkedHashMap.put(1, "Rakesh");
  12. linkedHashMap.put(2, "Raja");
  13. linkedHashMap.put(3, "Lenin");
  14.  
  15. System.out.println(linkedHashMap);
  16.  
  17. //get the value for the key
  18. System.out.println("getting the value at key 2");
  19. System.out.println(linkedHashMap.get(2));
  20.  
  21. //remove the value at key 2
  22. System.out.println("removing the value for key 2");
  23. linkedHashMap.remove(2);
  24.  
  25. Iterator iterator = linkedHashMap.entrySet().iterator();
  26. while (iterator.hasNext())
  27. {
  28. Map.Entry entry = (Map.Entry) iterator.next();
  29. Integer key = entry.getKey();
  30. String value = entry.getValue();
  31. System.out.println("Key " + key + " value " + value);
  32. }
  33. }
  34. }
  35.  
Output:
  1. {4=Chenchu, 1=Rakesh, 2=Raja, 3=Lenin}
  2. getting the value at key 2
  3. Raja
  4. removing the value for key 2
  5. Key 4 value Chenchu
  6. Key 1 value Rakesh
  7. Key 3 value Lenin
  8.  
Java TreeMap:
  • It implements Map Interface
  • It implements NavigableMap Interface.
  • It extends AbstractMap class.
  • It stores key/value pairs in sorted order
  • It contains values based on key
  • It contains only unique elements
  • It cannot have a null key
  • It can have multiple null values
Java TreeMap Constructors:
Constructor
Description
TreeMap()
It is the default constructor and it sorts the values based on the key.
TreeMap(Comparator comparator)
It creates an object and sorts the values based on the comparator specified. The key sorting logic would be present in the comparator.
TreeMap(Map map)
It creates an object using the elements present in the map.
TreeMap(SortedMap sortedMap)
It creates an object using the elements present in the sortedMap.
Java TreeMap Methods:
Method
Description
boolean containsKey(Object targetKey)
It returns true if the object contains the targetKey else it returns false.
boolean containsValue(Object targetValue)
It returns true if the map contains the targetValue else it returns false.
Object get(Object key)
It returns the object (value) associated with the key.
Object remove(Object targetKey)
It removes the key and value for the targetKey.
void putAll(Map existingMap)
It used to copy all the key and value pairs from the existing map to the target map.
Java TreeMap Example:
  1. public class TreeMapExample
  2. {
  3.  
  4. /*
  5. sorted order
  6. */
  7. public static void main(String[] args)
  8. {
  9. TreeMap treeMap = new TreeMap<>();
  10. //insert key and values
  11.  
  12. treeMap.put(4, "Chenchu");
  13. treeMap.put(1, "Rakesh");
  14. treeMap.put(2, "Raja");
  15. treeMap.put(3, "Lenin");
  16.  
  17. System.out.println(treeMap);
  18.  
  19. //get the value for the key
  20. System.out.println("getting the value at key 2");
  21. System.out.println(treeMap.get(2));
  22.  
  23. //remove the value at key 2
  24. System.out.println("removing the value for key 2");
  25. treeMap.remove(2);
  26.  
  27. Iterator iterator = treeMap.entrySet().iterator();
  28. while (iterator.hasNext())
  29. {
  30. Map.Entry entry = (Map.Entry) iterator.next();
  31. Integer key = entry.getKey();
  32. String value = entry.getValue();
  33. System.out.println("Key " + key + " value " + value);
  34. }
  35. }
  36. }
Output:
  1. {1=Rakesh, 2=Raja, 3=Lenin, 4=Chenchu}
  2. getting the value at key 2
  3. Raja
  4. removing the value for key 2
  5. Key 1 value Rakesh
  6. Key 3 value Lenin
  7. Key 4 value Chenchu

Java HashMap vs LinkedHashMap vs TreeMap:
HashMap
LinkedHashMap
TreeMap
It doesn't maintain any order.
It maintains insertion order.
It maintains sorted order. (Default: Ascending order)
It offers O(1) for insertion and lookup.
It offers O(1) for insertion and lookup.
It offers O(log N) for insertion and lookup.
It is implemented by an Array of LinkedLists.
It is implemented by doubly-linked buckets.
It is implemented by Red-Black Tree.

Java HashTable:
  • It inherits Dictionary class.
  • It implements Map interface.
  • Hashtable stores key/value pairs in a hash table
  • HashTable has its values in a bucket.
  • The position of the bucket is identified using hashcode().
  • It can contain only unique values.
  • It is Synchronized.
  • It may not have a null value or key.
  • Hashtable was part of the original java.util
  • Concrete implementation of a Dictionary
Java HashTable Constructors:
Constructor
Description
HashTable()
It is the default constructor.
HashTable(int size)
It creates a HashTable object by using the initial size.
HashTable(int size, int fillRatio)
It creates a HashTable object using the initial size and fill Ratio.
Java HashTable Methods:
Method
Description
void clear()
It removes all the elements.
boolean contains(Object testObject)
It returns true if the specified element is present else false.
boolean isEmpty()
It returns true if the HashTable doesn't contain any values.
Object get(Object targetKey)
It returns the Object that is associated with the target key.
Object remove(Object targetKey)
It removes the key and value that are associated with the target key.
int size()
It returns the size of the HashTable object.

Java HashMap vs HashTable:
HashMap
HashTable
It is Non-synchronized.
It is Synchronized.
It allows one null key and multiple null values.
It doesn't allow any null key or value
It was introduced in JDK 1.2.
It is a legacy class.
Performance is fast.
Performance is slow.

Java Stack:
  • A stack is a subclass of Vector
  • It implements a standard last-in, first-out stack
  • It has only default constructor
Java Stack Methods:
Constructor
Description
boolean empty()
It returns true if the stack doesn't have any values.
Object peek( )
It returns the topmost element from the stack but it doesn't remove the element.
Object pop( )
It returns the topmost element from the stack and removes it from the stack.
Object push(Object element)
It pushes the element on top of the stack.
int search(Object element)
It searches for the particular element and returns the position of it. If the element is not present in the stack then it returns -1.
Java Stack sample Implementation:
  1. public class StackExample
  2. {
  3. /*
  4. 1. last-in, first-out
  5. */
  6. public static void main(String[] args)
  7. {
  8. Stack stack=new Stack<>();
  9. stack.push("1");
  10. stack.push("2");
  11. stack.push("3");
  12. System.out.println(stack);
  13. System.out.println("Top most element "+stack.peek()); //returns the top most element without removing it.
  14. System.out.println("Top most element and then remove it "+stack.pop());// returns the top most element and then remove it.
  15. System.out.println("After removing top most element "+stack);
  16. }
  17. }

Java PriorityQueue:
  • PriorityQueue is introduced in Java 1.5 as a part of Java Collections.
  • java.util.PriorityQueue class is an unbounded priority queue based on a priority heap
  • The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
  • A priority queue does not permit null elements.
  • A priority queue relying on natural ordering also does not permit insertion of non-comparable objects.
Sample Implementation:
  1. public class PriorityQueueExample
  2. {
  3. /*
  4. 1. Natural ordering,
  5. 2. Can override the ordering using comparator
  6. */
  7. public static void main(String[] args)
  8. {
  9. PriorityQueue queue=new PriorityQueue<>();
  10. //1. add elements at the end
  11. queue.add("Rakesh");
  12. queue.add("Lenin");
  13. queue.add("Chenchu");
  14. //2. dispalying the elements
  15. System.out.println("");
  16. System.out.println(queue);
  17. System.out.println("peek------------");
  18. //3. peek - returns the head of the element but it doesn't remove it
  19. System.out.println(queue.peek());
  20. System.out.println("poll------------");
  21. //4. poll- returns the head of the element and removes it.
  22. System.out.println(queue.poll());
  23. System.out.println(queue);
  24. }
  25. }

Java Vector:
  • Implements a dynamic array
  • Vector is synchronized
  • Vector contains many legacy methods
  • Can dynamically change the size of a Vector at runtime.
When to use Vector?
  • When we don't know the size of the Array at runtime then we can use Vector because it can dynamically change the size at runtime.
Vector constructors:
Constructor
Description
Vector( )
It is the default constuctor which has an initial size of 10.
Vector(int size)
It creates an object by specifying the initial size.
Vector(int size, int increment)
It creates an object by specifying the initial size. Additionally, we need to specify the "increment" value. This "increment" value is added to existing size when the existing size gets exhausted.
Vector(Collection c)
It creates a Vector object by using the elements which are in the specified collection.
Java Vector Example:
Constructor
Description
void add(int index, Object element)
It inserts the specified object in the specified element.
boolean add(Object object)
It appends the specified object at the end of the Vector.
boolean addAll(Collection collection)
It appends all the elements of the collection at the end of the Vector.
boolean addAll(int index, Collection collection)
It appends all the elements of the collection from the specified index.
int capacity()
It returns the capacity of the Vector object.
void clear()
It removes all the elements from the Vector object.
boolean contains(Object testObject)
It returns true, if the testObject is in the Vector object.
int size()
It returns the size of the Vector object.
boolean remove(Object targetObject)
It returns the first occurece of the target object.
void removeElementAt(int index)
It removes the object at the specified index.
Java Vector Example:
  1. public class VectorExample
  2. {
  3. /*
  4. 1. Vector are similar to ArrayList
  5. 2. Vectors are synchronized but ArrayList is not synchronized.
  6. 3. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
  7. */
  8. public static void main(String[] args)
  9. {
  10. Vector books = new Vector<>();
  11.  
  12. System.out.println("Books size " + books.size());
  13.  
  14. books.add("C"); // C
  15. books.add("C++"); // C C++
  16. books.add("Java"); // C C++ Java
  17.  
  18. System.out.println("Books size " + books.size());
  19.  
  20. System.out.println(books.toString());
  21.  
  22. // C[0] C++[1] Java[2] existing
  23. books.add(1, "Python"); //C[0] Python[1] C++[2] Java[3] New
  24.  
  25. System.out.println(books.toString());
  26.  
  27. //C[0] Python[1] C++[2] Java[3] Existing
  28. System.out.println("Removing C book");
  29. books.remove("C");
  30. //Python[0] C++[1] Java[2] New
  31.  
  32. System.out.println("Books after removing C =" + books.toString());
  33. }
  34. }
In Java, we can have two options to transfer bulk objects in between method calls; either as arguments or return values.
  1. By Java array (Ex. Employee employees[] =…)
  2. By Java Collection object (Ex. ArrayList employees = … )
The Java array type is good in simple cases but it may not be suitable for many cases in real-time projects.
Case Study : Sorting
Consider an application that requires sorting in your page where we can easily sort java.util.Collection by calling simple method call. But in the case of array type we need to either rely on database query for sorting or in your Java algorithm .
This type of design may impact your application’s performance since you need to call again for your back-end for sorting.
Case Study: Key Sorting
Consider another use case where you need to store key-value pair where keys alone will be sorted for UI display. We can use HaspMap to store key-value pair and keys can be accessed by keySet() method.
The collection util package usages/advantages:
  • Easy indexing
  • Easy to resize (arrays cannot be resized once created)
  • Easy sorting
  • Delete/Add an object can be dynamic
  • Key-Value pair type collections
  • Easy to transfer between application tiers
  • Easy to display in JSF/JSP pages by simple tags
Real time example:
We have used HashMap to fetch random questions for MyExamCloud exams.
You can take a look on Java Certifications MyExamCloud Exam Collections and understand about how MyExamCloud Question objects are fetched when a user take a test.
Contact me if you have any help on Java related questions.
Requirement : To store Order details.
Map<String,Order> unique order-id mapped with orderDetails
List<Map<String,Order>> all orders.
Requirement : To implement functionality like sorting which we see in All ecommerce websites like sort by
Prize low to high
Avg customer rating
Blah blah
You can use custom comparator for this. You can try coding for this.
Requirement : suppose you have 100 pages of records of customer data, how to show it page wise in which one page can contain 30 rows
Hint : Pagination concept, you can implement it with simple Lists
There are lot more scenarios than this, which can be solved using Collections

  • Arrays are not resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
In other words, Java Collections Framework allows you to use the right data structure, because one size does not fit all.

java collections are used to store values of many objects in a web app
i am taking examples of websites
u can take example of an web site login page in which u have input many values…instead of taking values from an app every time its better to use to collections which would be easy..
another example in website is when u want to insert values into dropdownlist it will very useful…

Collections are useful in those situations where you doesn't know how much data you have to handled, that means size of data not defined. Like there are so many scenario when data dynamically comes from UI or application ( no fixed size defined) then you must use collections to manage and perform diff operations.
In real time some times we can't estimate the size of the data and type of the data it's better to maintain data as objects through collections.through arrays we can't manage the data because arrays are not auto-grow-able in size.
through collections we can use our required data structures directly. we have different classes for that. in each we have predefined methods to manipulate data in that collection.
Collections are performance wise slow. even though collections provide more features to maintain huge data easily.
Reference : 
Collection Framework - Collection Framework provides important interfaces and classes using which we can manage a group of objects.
Collections comes in the advance topics of Core Java and you shouldn't miss it for interviews. Some of the most important classes in Collection Framework are-
  • ArrayList - It is like a dynamic array i.e. we don't need to declare its size, itgrows as we add elements to it and it shrinks as we remove elements from it, during the runtime of the programFor more you may read ArrayList in Java- Decodejava.com
  • LinkedList - It can be used to depict a Queue(FIFO) or even a Stack(LIFO). For more on LinkedList with simple code examplesyou may read LinkedList in Java- Decodejava.com
  • HashSet - It stores its element by a process called hashing. The order of elements in HashSet is not guaranteedFor more on HashSet with simple code examples, you may read HashSet in Java- Decodejava.com
  • TreeSet - TreeSet is the best candidate when one needs to store a large number of sorted elements and their fast accessFor more on TreeSet with easy code examples, you may read TreeSet in Java- Decodejava.com
  • ArrayDeque - It can also be used to implement a first-in, first-out(FIFO) queue or a last-in, first-out(LIFO) queue. For more on ArrayDeque with code example, you may follow ArrayDeque Class
  • HashMap - HashMap stores the data in the form of key-value pairs, where key and value are objects. For HashMap with code examples, you may readHashMap in Java - Decodejava.com
  • Treemap - TreeMap stores key-value pairs in a sorted ascending order and retrieval speed of an element out of a TreeMap is quite fast. For more on TreeMap through simple code, you may read TreeMap in Java - Decodejava.com
Collection Framework is one of the most important topics and it’s a little time consuming but eventually hard work pays off.


Collections allocate memory dynamically, i.e. they do not have a fixed size.
So, collections are used in scenarios where size is not fixed. Data are in form of Key-value pairs.
For example,
  • Number of likes on a picture you have posted on Facebook
  • Key value pairs for roll no. and name of students
  • Sorting in lists like Country selection
To learn more about Collections Check out this Collections blog
  • Arrays are not resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
In other words, Java Collections Framework allows you to use the right data structure, because one size does not fit all.

  • Arrays are not resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map , whether backed by a red-black tree or a hashtable.
In other words, Java Collections Framework allows you to use the right data structure, because one size does not fit all. 

Q : What are Collection related features in Java 8?

Java 8 has brought major changes in the Collection API. Some of the changes are:
  1. Java Stream API for collection classes for supporting sequential as well as parallel processing
  2. Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because it’s argument Consumer is a function interface.
  3. Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method inIterator interface, Map replaceAll()compute()merge() methods.
Q : What is Java Collections Framework? List out some benefits of Collections framework?
Collections are used in every programming language and initial java release contained few classes for collections: VectorStackHashtableArray. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.
Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.
Some of the benefits of collections framework are;
  • Reduced development effort by using core collection classes rather than implementing our own collection classes.
  • Code quality is enhanced with the use of well tested collections framework classes.
  • Reduced effort for code maintenance by using collection classes shipped with JDK.
  • Reusability and Interoperability
Q :  What is the benefit of Generics in Collections Framework?
Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.

Q : What are the basic interfaces of Java Collections Framework?

Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface. 
Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards. 
List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.
Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Some other interfaces are QueueDequeueIteratorSortedSetSortedMap and ListIterator.
Q : Why Collection doesn’t extend Cloneable and Serializable interfaces?
Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t.
A lot of the Collection implementations have a public clone method. However, it does’t really make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation.
The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.
So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.

Q : What is difference between fail-fast and fail-safe?
Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
Q : How to avoid ConcurrentModificationException while iterating a collection?
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
Q : What is difference between ArrayList and vector?
  • Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
  • Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

How can Arraylist be synchronized without using Vector?

Arraylist can be synchronized using:

     Collection.synchronizedList(List list)

Other collections can be synchronized:
      Collection.synchronizedMap(Map map)
    Collection.synchronizedCollection(Collection c)

If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

  1. Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
  2. Now call Collections.sort() method and pass list as an argument.

How about when Employee class is a jar file and you do not have access to its source code?

  • Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
  • Call Collections.sort() on the list and pass Comparator as an argument.

What is difference between HashMap and HashTable?

Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
  • HashMap is not synchronized in nature but HashTable is.
  • Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
  • HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

What are the prominent implementation of List interface?

The classes that implement List interface:
  • ArrayList: It is a re sizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
  • Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
  • LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Which all classes implement Set interface?
  • SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  • TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
  • HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

What is difference between List and a Set?

  • List can contain duplicate values but Set doesnt allow. Set allows only to unique elements. 
  • List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)

What is difference between Arrays and ArrayList ?

  • Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as:
    int [] intArray= new int[6];
    intArray[7]   // will give ArraysOutOfBoundException.
  • Also the size of array cannot be incremented or decremented. But with ArrayList the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
    List list = new ArrayList();
    list.add(1);
    list.add(3);
    list.remove(0) // will remove the element from the 1st location. 
  • ArrayList is one dimensional but array can be multidimensional.
    int [][][] intArray= new int[3][2][1];   // 3 dimensional array   
  • To create an array the size should be known or initialized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory. 

When to use ArrayList or Linked List ?


Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Consider a scenario. If an ArrayList has to be iterated to read data only, what are the possible ways and which is the fastest?

It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.

For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Which design pattern Iterator follows?

It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.

Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Is it better to have a HashMap with large number of records or n number of small hashMaps?

It depends on the different scenario one is working on:
  • If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
  • If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();

It is preferred because
  • If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that. 
  • The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
  • When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible

What is difference between iterator access and index access?

  • Index based access allow access of the element directly on the basis of index. The cursor of the data structure can directly goto the 'n' location and get the element. It does not traverse through n-1 elements.
  • In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
  • Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
  • Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
  • Traversal or search in index based datastructure is faster.
  • ArrayList is index access and LinkedList is iterator access. 

How to sort list in reverse order?

To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
      List list = new ArrayList();
    Comparator comp = Collections.reverseOrder();
    Collections.sort(list, comp)

Can a null element added to a Treeset or HashSet?

A null element can be added only if the TreeSet contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element.

How to sort list of strings - case insensitive?

using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

How to make a List (ArrayList,Vector,LinkedList) read only?

A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

What is ConcurrentHashMap?

A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

Which is faster to iterate LinkedHashSet or LinkedList?

LinkedList.

Which data structure HashSet implements

HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap

HashMap is fastest, ConcurrentHashMap, Collections.synchronizedMap, HashTable.

What is identityHashMap?

The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

What is WeakHashMap?

A Hashtable based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

What are basic rules, which govern creation of immutable classes? 

· Declare the class final.

· Declare all data private.

· Provide only getter methods and no setter methods.

· Set all instance data in the constructor.

· Clone mutable objects for which a reference to them is returned.

· Clone mutable objects for which a reference to them is received. 

· Implement a deep clone if the default shallow clone is not correct for a properly    behaved immutable object.



Difference between HashMap and HashTable / HashMap vs HashTable 

1. Synchronization or Thread Safe:  This is the most important difference between two. HashMap is non-synchronized and not thread safe. On the other hand, HashTable is thread safe and synchronized.

When to use HashMap?  Answer: is if your application do not require any multi-threading task, in other words HashMap is better for non-threading applications. HashTable should be used in multithreading applications. 


2. Null keys and null values :  HashMap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.


3. Iterating the values:  HashMap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.


4.  Fail-fast iterator: The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.
 if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModificationException.
Structural modification means adding or removing elements from the Collection object (here HashMap or Hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast. 


5. Performance:  HashMap is much faster and uses less memory than Hashtable as former is unsynchronized. Unsynchronized objects are often much better in performance in compare to synchronized  object like Hashtable in single threaded environment.


6. Superclass and Legacy :  Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map"  abstract data type.

Example of HashMap and HashTable 

import java.util.Hashtable;

public class HashMapHashtableExample {
   
    public static void main(String[] args) {
 
        Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
        hashtableobj.put("Alive is ", "awesome");
        hashtableobj.put("Love", "yourself");
        System.out.println("Hashtable object output :"+ hashtableobj);

        HashMap hashmapobj = new HashMap();
        hashmapobj.put("Alive is ", "awesome"); 
        hashmapobj.put("Love", "yourself");
        System.out.println("HashMap object output :"+hashmapobj);  

 }
}

Output :  Hashtable object output :{Love=yourself, Alive is =awesome}
                 HashMap object output :{Alive is =awesome, Love=yourself}
    
Similarities Between HashMap and Hashtable

1. Insertion Order :   Both HashMap and Hashtable  does not guarantee that  the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
2. Map interface :   Both HashMap and Hashtable implements Map interface .


3. Put and get method :  Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.


4. Internal working :  Both HashMap and Hashtable works on the Principle of Hashing .

When to use HashMap and Hashtable?

1. Single Threaded Application:  HashMap should be preferred over Hashtable for the non-threaded applications. In simple words, use HashMap in unsynchronized or single threaded applications.

2. Multi-Threaded Application:  We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8. Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.

Recap: Difference between HashMap and Hashtable in Java  

HashMap
Hashtable
Synchronized
No
Yes
Thread-Safe
No
Yes
Null Keys and Null values
One null key ,Any null values
Not permit null keys and values
Iterator type
Fail fast iterator
Fail safe iterator
Performance
Fast
Slow in comparison
Superclass and Legacy
Abstract Map , No
Dictionary , Yes


Difference between Array and ArrayList in Java with Example
1. Resizable:   Array is static in size that is fixed length data structure, One cannot change the length after creating the Array object.
ArrayList is dynamic in size. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. As elements are added to an ArrayList its capacity grows automatically.


2. Performance: Performance of Array and ArrayList depends on the operation you are performing:
resize() operation : Automatic resize of ArrayList will slow down the performance as it will use temporary array to copy elements from the old array to new array.


ArrayList is internally backed by Array during resizing  as it calls the native implemented method System.arrayCopy (src,srcPos,dest,destPos,length) .
add() or get() operation : adding an element or retrieving an element from the array or ArrayList object has almost same  performance , as for ArrayList object these operations  run in constant time.


3. Primitives:  ArrayList cannot contains primitive data types (like int , float , double) it can only contains Object while Array can contain both primitive data types as well as objects.


One get a misconception that we can store primitives (int,float,double) in ArrayList , but it is not true. Suppose we have ArrayList object,
ArrayList alist = new ArrayList ();
alist.add(23); //try to add primitive
JVM through Autoboxing (converting primitives to equivalent objects internally) ensures that only objects are added to the arraylist object. 
thus , above step internally works like this :

alist . add(new Integer(23));

4. Iterating the values: We can use iterator  to iterate through ArrayList . The iterators returned by the ArrayList class's iterator and listiterator method are fail-fast.  We can use for loop or for each loop to iterate through array .  

5. Type-Safety:  In Java , one can ensure Type Safety through Generics. while Array is a homogeneous data structure , thus it will contain objects of specific class or primitives of specific  data type. In array if one try to store the different data type other than the specified while creating the array object , ArrayStoreException is thrown.


Example :  String temp [] = new String [2]; // creates a string array of size 2
temp [0] = new Integer (12); // throws ArrayStoreException,
 trying to add Integer object in String[] 

6. Length:  Length of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array.
for example :
Integer arrayobject[] = new Integer[3];
arraylength= arrayobject.length   ;  //uses arrayobject length variable

ArrayList  arraylistobject = new ArrayList();
arraylistobject.add(12);
arraylistobject.size();   
//uses arraylistobject size method

7. Adding elements: We can insert elements into the arraylist object using the add() method while  in array we insert elements using the assignment operator.

Integer addarrayobject[] = new Integer[3];
addarrayobject[0]= new Integer(8)   ;  //new object is added to the array object

8. Multi-dimensional:  Array can be multi-dimensional, while ArrayList is always single dimensional.
Example of multidimensional array:
Integer addarrayobject[][] = new Integer[3][2];
addarrayobject[0][0]= new Integer(8)  

Example of Array and ArrayList  
import java.util.ArrayList;
import java.util.Iterator;

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

        // ArrayList Example  
        ArrayList<String> arrlistobj = new ArrayList<String>();
        arrlistobj.add("Alive is awesome");
        arrlistobj.add("Love yourself");
        Iterator it = arrlistobj.iterator();
        System.out.print("ArrayList object output :"); 
        while(it.hasNext())        
          System.out.print(it.next() + " ");               
        // Array Example
        String[] arrayobj = new String[3];
        arrayobj[0]= "Love yourself"; 
        arrayobj[1]= "Alive is awesome";
        arrayobj[2]= "Be in Present";
        System.out.print("Array object output :");
        for(int i=0; i < arrayobj.length ;i++)
        System.out.print(arrayobj[i] + " ");  

 }
}

Output :  ArrayList object output :{ Alive is awesome , Love yourself }
                 Array object output :{ Love yourself , Alive is awesome, Be in present}

Similarities Between Array and ArrayList

1. add and get method : Performance of Array and ArrayList are similar for the add and get operations .Both operations runs in constant time.

2. Duplicate elements : Both array and arraylist can contain duplicate elements.

3. Null Values : Both can store null values and uses index to refer to their elements.

4. Unordered :  Both does not guarantee ordered  elements.

Difference between Array and ArrayList in Java  


Array
ArrayList
Resizable
No
Yes
Primitives
Yes
No
Iterating values
for, for each
Iterator , for each
Length
length variable
size method
Performance
Fast
Slow in comparison
Multidimensional
Yes
No
Add Elements
Assignment operator
add method


Difference between HashSet and TreeSet 

1. Ordering: HashSet stores the object in random order. There is no guarantee that the element we inserted first in the HashSet will be printed first in the output. For example   
import java.util.HashSet;
public class HashSetExample {
        public static void main(String[] args) {
                HashSet<String> obj1= new HashSet<String>();
             obj1.add("Alive");
            obj1.add("is");
            obj1.add("Awesome");
            System.out.println(obj1);       
    }   
}
 OUTPUT : [is, Awesome, Alive]  
Elements are sorted according to the natural ordering of its elements in TreeSet. If the objects can not 
be sorted in natural order than use 
compareTo() method to sort the elements of TreeSet object .
import java.util.TreeSet;
public class TreeSetExample { 
    public static void main(String[] args) {
                TreeSet<String>  obj1= new TreeSet<String>();
        obj1.add("Alive");
        obj1.add("is");
        obj1.add("Awesome");
        System.out.println(obj1);
        }    }
    OUTPUT : [Alive, Awesome, is]

2. Null value :   HashSet can store null object while TreeSet does not allow null object. If one try to store null object in TreeSet object , it will throw Null Pointer Exception.

3. Performance : HashSet take constant time performance for the basic operations like add, remove contains and  size.While TreeSet guarantees log(n) time cost for the basic operations (add,remove,contains).

4. Speed : HashSet is much faster than TreeSet,as performance time of HashSet is constant against the log time of TreeSet for most operations (add,remove ,contains and size) . Iteration performance of HashSet mainly depends on the load factor and initial capacity parameters. 

5. Internal implementation :  As we have already discussed How hashset internally works in java thus, in one line HashSet are internally backed by hashmap. While TreeSet is backed by a  Navigable  TreeMap. 
6. Functionality :    TreeSet is rich in functionality as compare to HashSet. Functions like pollFirst(),pollLast(),first(),last(),ceiling(),lower() etc. makes TreeSet easier to use than HashSet. 

7. Comparision : HashSet uses equals() method for comparison in java while TreeSet uses compareTo() method for maintaining ordering .



To whom priority is given TreeSet comparator or Comparable.compareTo() .

Suppose there are elements in TreeSet which can be naturally sorted by the TreeSet , but we also added our own sorting method by implementing Comparable interface compareTo() method .
Then to whom priority is given.


Answer to the above question is that the Comparator passed into the TreeSet constructor has been given priority.

public TreeSet(Comparator comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.

   Parameters:
 comparator - the comparator that will be used to order this set. If null, the natural ordering of the elements will be used.

Similarities Between HashSet and TreeSet

1. Unique Elements :   Since HashSet and TreeSet both implements Set interface . Both are allowed to store only unique elements in their objects. Thus there can never be any duplicate elements inside the HashSet and TreeSet objects.

2. Not Thread Safe : HashSet and TreeSet both are not synchronized or not thread safe.HashSet and TreeSet, both implementations are not synchronized. If multiple threads access a hash set/ tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

3. Clone() method copy technique:  Both HashSet and TreeSet uses shallow copy technique to create a clone of  their objects .

4. Fail-fast Iterators :  The iterators returned by this class's  method are fail-fast: if the set is modified at any time after the iterator is  created, in any way except through the iterator's own  remove method, the iterator will throw a  ConcurrentModificationException.  Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at   an undetermined time in the future.

When to prefer TreeSet over HashSet

1.  Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order.


2.   TreeSet has greater locality than HashSet.

If two entries are nearby in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to. 
     
As we know Data reads from the hard drive takes much more latency time than data read from the cache or memory. In case data needs to be read from hard drive than prefer TreeSet as it has greater locality than HashSet.

3. TreeSet uses Red- Black tree algorithm underneath to sort out the elements. When one needs to perform read/write operations frequently, then TreeSet is a good choice.



6 comments:

  1. Nice article well explained . there is good linkedlist examples collection
    visit Java Linked list examples

    ReplyDelete
  2. Thanks for sharing this informative content , Great work
    Creative Thinking for creating an impact!
    Product Thinking Community introduces PT Labs powered by Leanpitch
    Devops Online Training

    ReplyDelete
  3. Thanks for sharing this informative content , Great work
    To crack scrum master interview : Scrum Master Interview Questions

    ReplyDelete
  4. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
    ICP-CAT certification

    ReplyDelete
  5. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
    ICP-CAT certification

    ReplyDelete
  6. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product Management Launchpad during this lockdown period everyone can use it wisely.
    Product Management Workshop

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...