Generic and collection

By ukmodak | March 31st 2024 10:34:01 AM | viewed 783 times

What is Generic?

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.

Now generics, forces the java programmer to store specific type of objects.

We can store any type of objects in collection i.e. non-generic

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

  • Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
  • Type casting is not required: There is no need to typecast the object.
  •         List list = new ArrayList();  
            list.add("hello");  
            String s = list.get(0);  
      
  • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
  • 		List<String> list = new ArrayList<String>();  
    		list.add("hello");  
    		list.add(32);//Compile Time Error  
      
    	Syntax to use generic collection
    
    	      ClassOrInterface<Type>  
    
    	Example to use Generics in java
    
    	       ArrayList<String> 
      

Full Example of Generics in Java

Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap , Comparator etc.

 import java.util.*;  
 class TestGenerics1{  
	    public static void main(String args[]){  
			   ArrayList<String> list=new ArrayList<String>();  
			    list.add("rahul");  
			    list.add("jai");  
				
			       //list.add(32);//compile time error  
			      
			    String s=list.get(1);//type casting is not required 
				
			    System.out.println("element is: "+s);  
			      
			    Iterator<String> itr=list.iterator();
				
			    while(itr.hasNext()){  
				
			    System.out.println(itr.next());  
			    }  
	    }  
    }  
 
 Output:element is: jai
       rahul
       jai 
 

Example of Java Generics using Map

Now we are going to use map elements using generics. Here, we need to pass key and value. Let us understand it by a simple example

import java.util.*;  
class TestGenerics2{  
    public static void main(String args[]){  
		    Map<Integer,String> map=new HashMap<Integer,String>();  
		    map.put(1,"vijay");  
		    map.put(4,"umesh");  
		    map.put(2,"ankit");  
		      
		       //Now use Map.Entry for Set and Iterator  
		    Set<Map.Entry<Integer,String>> set=map.entrySet();  
		      
		    Iterator<Map.Entry<Integer,String>> itr=set.iterator();  
		    while(itr.hasNext()){  
		    Map.Entry e=itr.next();//no need to typecast  
		    System.out.println(e.getKey()+" "+e.getValue());  
		    }  
      
    }
}  
 
 Output:1 vijay
       2 ankit 
       4 umesh
 

Type Parameters

The type parameters naming conventions are important to learn generics thoroughly. The commonly type parameters are as follows:

  1. T - Type
  2. E - Element
  3. K - Key
  4. N - Number
  5. V - Value

Generic class

A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type.

Let’s see the simple example to create and use the generic class.

    class MyGen<T>{  
    T obj;  
    void add(T obj){this.obj=obj;}  
    T get(){return obj;}  
    }  
 

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you specify for the class, will be used to store and retrieve the data.

What is Collection in Java

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is a framework in Java

  • It provides readymade architecture
  • It represents a set of classes and interfaces
  • It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:

  • Interfaces and its implementations, i.e., classes
  • Algorithm

Hierarchy of Collection Framework

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap

    Collection Classes
  1. ArrayList
  2. LinkedList
  3. HashSet
  4. LinkedHashSet
  5. TreeSet
  6. PriorityQueue
  7. ArrayDeque

ArrayList

Java ArrayList class can contain duplicate elements.

Java ArrayList class maintains insertion order.

Java ArrayList class is non synchronized.

Java ArrayList allows random access because array works at the index basis.

In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.

Methods of Java ArrayList
import java.util.*;  
class ArrayList1{  
   public static void main(String args[]){  
      ArrayList list=new ArrayList();    //Creating arraylist    
          list.add("Ravi");                              //Adding object in arraylist    
          list.add("Vijay");    
          list.add("Ravi");    
          list.add("Ajay");    
                      //Invoking arraylist object   
          System.out.println(list);  
      }  
     }  
    }  
Figure:1
Method Example Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection iterator.
boolean addAll(int index, Collection<? extends E> c) It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an ArrayList instance.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order.
T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the correct order
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> filter) It is used to remove all the elements from the list that satisfies the given predicate.
protected void removeRange(int fromIndex, int toIndex) It is used to remove all the elements lies within the given range.
void replaceAll(UnaryOperator<E> operator) It is used to replace all the elements from the list with the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified collection
E set(int index, E element) It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the given range.
int size() It is used to return the number of elements present in the list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's current size.

Ways to iterate the elements of the collection in java

There are various ways to traverse the collection elements:

  1. By Iterator interface.
  2. By for-each loop.
  3. By ListIterator interface
  4. By for loop.
  5. By forEach() method.
  6. By forEachRemaining() method.
Example:
import java.util.*;  
class ArrayList2{  
     public static void main(String args[]){  
      ArrayList list=new ArrayList();//Creating arraylist  
      list.add("Ravi");//Adding object in arraylist  
      list.add("Vijay");  
      list.add("Ravi");  
      list.add("Ajay"); 

	  
	 System.out.println("Traversing list through Iterator");  
      Iterator itr=list.iterator();  
      while(itr.hasNext()){  
       System.out.println(itr.next()); 
      } 
	  
 
	System.out.println("Traversing list through for-each loop"); 
	  for(String obj:al)  
	    System.out.println(obj);  
	 }  
	 
	   System.out.println("Traversing list through List Iterator:");  
            //Here, element iterates in reverse order  
              ListIterator<String> list1=list.listIterator(list.size());  
              while(list1.hasPrevious())  
              {  
                  String str=list1.previous();  
                  System.out.println(str);  
              }  
        System.out.println("Traversing list through for loop:");  
           for(int i=0;i<list.size();i++)  
           {  
            System.out.println(list.get(i));     
           }  
              
        System.out.println("Traversing list through forEach() method:");  
             //The forEach() method is a new feature, introduced in Java 8.  
            list.forEach(a->{                   //Here, we are using lambda expression  
                   System.out.println(a);  
              });  
                
        System.out.println("Traversing list through forEachRemaining() method:");  
              Iterator<String> itr=list.iterator();  
              itr.forEachRemaining(a->         //Here, we are using lambda expression  
              {  
                      System.out.println(a);  
              });  

	  
   }  
}  

Java ArrayList Serialization and Deserialization Example

Let's see an example to serialize an ArrayList object and then deserialize it

    import java.io.*;  
    import java.util.*;  
     class ArrayList6 {  
      
            public static void main(String [] args)  
            {  
              ArrayList al=new ArrayList();  
              al.add("Ravi");    
              al.add("Vijay");    
              al.add("Ajay");    
                
              try  
              {  
                  //Serialization  
                  FileOutputStream fos=new FileOutputStream("file");  
                  ObjectOutputStream oos=new ObjectOutputStream(fos);  
                  oos.writeObject(al);  
                  fos.close();  
                  oos.close();  
                  //Deserialization  
                  FileInputStream fis=new FileInputStream("file");  
                  ObjectInputStream ois=new ObjectInputStream(fis);  
                ArrayList  list=(ArrayList)ois.readObject();  
                System.out.println(list);    
              }catch(Exception e)  
              {  
                  System.out.println(e);  
              }  
           }  
        }         
[Ravi, Vijay, Ajay]

LinkedList

Java LinkedList class can contain duplicate elements.

Java LinkedList class maintains insertion order.

Java LinkedList class is non synchronized.

In Java LinkedList class, manipulation is fast because no shifting needs to occur.

Java LinkedList class can be used as a list, stack or queue.

Methods of Java LinkedList
import java.util.*;  
public class LinkedList1{  
   public static void main(String args[]){  
      
      LinkedList al=new LinkedList();  
      al.add("Ravi");  
      al.add("Vijay");  
      al.add("Ravi");  
      al.add("Ajay");  
      
      Iterator itr=al.iterator();  
      while(itr.hasNext()){  
       System.out.println(itr.next());  
      }  
     }  
    }  
Figure:2
Method Example Description
boolean add(E e) It is used to append the specified element at the end of a list.
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection iterator.
boolean addAll(int index, Collection<? extends E> c) It is used to append all the elements in the specified collection, starting at the specified position of the list.
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
void clear() It is used to remove all of the elements from this list.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
Iterator descendingIterator() It is used to return an iterator over the elements in a deque in reverse sequential order.
E element() It is used to retrieve the first element of a list.
E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.
E getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.
ListIterator listIterator(int index) It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.
boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E e) It inserts the specified element at the front of a list.
boolean offerLast(E e) It inserts the specified element at the end of a list.
E peek() It retrieves the first element of a list
E peekFirst() It retrieves the first element of a list or returns null if a list is empty.
E peekLast() It retrieves the last element of a list or returns null if a list is empty.
E poll() It retrieves and removes the first element of a list.
E pollFirst() It retrieves and removes the first element of a list, or returns null if a list is empty.
E pollLast() It retrieves and removes the last element of a list, or returns null if a list is empty.
E pop() It pops an element from the stack represented by a list.
void push(E e) It pushes an element onto the stack represented by a list.
void push(E e) It pushes an element onto the stack represented by a list.
E remove() It is used to retrieve and removes the first element of a list.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
E removeFirst() It removes and returns the first element from a list.
boolean removeFirstOccurrence(Object o) It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).
E removeLast() It removes and returns the last element from a list.
boolean removeLastOccurrence(Object o) It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).
E set(int index, E element) It replaces the element at the specified position in a list with the specified element.
Object[] toArray() It is used to return an array containing all the elements in a list in proper sequence (from first to the last element).
T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.
int size() It is used to return the number of elements in a list.

Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes

However, there are many differences between ArrayList and LinkedList classes that are given below

ArrayList internally uses a dynamic array to store the elements. LinkedList internally uses a doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
An ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Java List Interface

List Interface is the subinterface of Collection. It contains index-based methods to insert and delete elements. It is a factory of ListIterator interface.

List Interface declaration
     public interface List extends Collection 
       example:
        List al=new ArrayList();  	   
 
Figure:3
Method Example Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of a list.
void clear() It is used to remove all of the elements from this list.
boolean equals(Object o) It is used to compare the specified object with the elements of a list.
int hashcode() It is used to return the hash code value for a list.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order.
T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the correct order.
boolean contains(Object o) It returns true if the list contains the specified element
boolean containsAll(Collection <?< c)) It returns true if the list contains all the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection <?> c) It is used to remove all the elements from the list
void replaceAll(UnaryOperator operator) It is used to replace all the elements from the list with the specified element.
void retainAll(Collection ,span><?> c) It is used to retain all the elements in the list that are present in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator <? super E> c) It is used to sort the elements of the list on the basis of specified comparator.
Spliterator spliterator() It is used to create spliterator over the elements in a list.
List subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the given range.
int size() It is used to return the number of elements present in the list.

Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet allows null value.
  • HashSet class is non synchronized
  • HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • HashSet is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

HashSet class declaration
     public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
	 
	 example:
	  HashSet set=new HashSet();  
 
Figure:4
Modifier & Type Method Description
boolean add(E e) It is used to add the specified element to this set if it is not already present.
void clear() It is used to remove all of the elements from the set.
object clone() It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean isEmpty() It is used to return true if this set contains no elements.
Iterator iterator() It is used to return an iterator over the elements in this set.
Iterator iterator() It is used to return an iterator over the elements in this set.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
int size() It is used to return the number of elements in the set.
Spliterator spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

LinkedHashSett

Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface

The important points about Java LinkedHashSet class are::

  • Java LinkedHashSet class contains unique elements only like HashSet
  • Java LinkedHashSet class provides all optional set operation and permits null elements
  • Java LinkedHashSet class is non synchronized
  • Java LinkedHashSet class maintains insertion order.
LinkedHashSet class declaration
    public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable  
	 
	 example:
	 LinkedHashSet set=new LinkedHashSet();  
 

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.

The important points about Java TreeSet class are:

  • Java TreeSet class contains unique elements only like HashSet.
  • Java TreeSet class access and retrieval times are quiet fast
  • Java TreeSet class doesn't allow null element.
  • Java TreeSet class is non synchronized
  • Java TreeSet class maintains ascending order
TreeSet class declaration
   public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, Serializable  
	 example:
	 TreeSet al=new TreeSet(); 
 
figure-5
Method Description
boolean add(E e) It is used to add the specified element to this set if it is not already present.
boolean addAll(Collection c) It is used to add all of the elements in the specified collection to this set.
E ceiling(E e) It returns the equal or closest greatest element of the specified element from the set, or null there is no such element.
Comparator comparator() It returns comparator that arranged elements in order.
Iterator descendingIterator() It is used iterate the elements in descending order.
NavigableSet descendingSet() It returns the elements in reverse order.
E floor(E e) It returns the equal or closest least element of the specified element from the set, or null there is no such element.
SortedSet headSet(E toElement) It returns the group of elements that are less than the specified element.
NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element.
E higher(E e) It returns the closest greatest element of the specified element from the set, or null there is no such element.
Iterator iterator() It is used to iterate the elements in ascending order.
E lower(E e) It returns the closest least element of the specified element from the set, or null there is no such element.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over the elements.
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) It returns a set of elements that lie between the given range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given range which includes fromElement and excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal to the specified element.
NavigableSet tailSet(E fromElement, boolean inclusive) It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean isEmpty() It returns true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void clear() It is used to remove all of the elements from this set.
Object clone() It returns a shallow copy of this TreeSet instance.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.

Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

HashMap

Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap class and implements Map interface.

Points to remember

  • Java HashMap class contains values based on the key.
  • Java HashMap class contains only unique keys.
  • Java HashMap class may have one null key and multiple null values.
  • Java HashMap class is non synchronized.
  • Java HashMap class maintains no order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
HashMap class declaration
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable  

example:
HashMap hm=new HashMap();   

Methods of Java HashMap class

Method Description
void clear() It is used to remove all of the mappings from this map.
boolean isEmpty() It is used to return true if this map contains no key-value mappings.
Object clone() It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() It is used to return a collection view of the mappings contained in this map.
Set keySet() It is used to return a set view of the keys contained in this map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.

Java LinkedHashMap class

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.

Points to remember

  • Java LinkedHashMap contains values based on the key.
  • Java LinkedHashMap contains unique elements.
  • Java LinkedHashMap may have one null key and multiple null values.
  • Java LinkedHashMap is non synchronized.
  • Java LinkedHashMap maintains insertion order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

LinkedHashMap class declaration

  public class LinkedHashMap extends HashMap implements Map
  example:
   LinkedHashMap hm=new LinkedHashMap(); 

Methods of Java LinkedHashMap class

Method Description
V get(Object key) It returns the value to which the specified key is mapped.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
Set> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set keySet() It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry eldest) It returns true on removing its eldest entry.
void replaceAll(BiFunction function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a Collection view of the values contained in this map.

Java TreeMap class

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

  • Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • Java TreeMap contains only unique elements.
  • Java TreeMap cannot have a null key but can have multiple null values.
  • Java TreeMap is non synchronized.
  • Java TreeMap maintains ascending order.
TreeMap class declaration
public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializab

example:
TreeMap map=new TreeMap();

Methods of Java TreeMap class

Method Description
Map.Entry ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet descendingKeySet() It returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
SortedMap headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if this map contains a mapping for the specified key.
Set keySet() It returns the collection of keys exist in the map.
Map.Entry lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry lowerEntry(K key) It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet navigableKeySet() It returns a NavigableSet view of the keys contained in this map.
Map.Entry pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry pollLastEntry() It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with the specified key in the map.
void putAll(Map map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key-value pairs whose keys range from fromKey to toKey.
SortedMap subMap(K fromKey, K toKey) It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(K fromKey) It returns key-value pairs whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive) It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
K firstKey() It is used to return the first (lowest) key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last (highest) key currently in the sorted map.
V remove(Object key) It removes the key-value pair of the specified key from the map.
Set> entrySet() It returns a set view of the mappings contained in the map.
int size() It returns the number of key-value pairs exists in the hashtable.
Collection values() It returns a collection view of the values contained in the map.

Java Hashtable class

Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface.

Points to remember

  • A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
  • Java Hashtable class contains unique elements.
  • Java Hashtable class doesn't allow null key or value.
  • Java Hashtable class is synchronized.
  • The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Hashtable class declaration

public class Hashtable extends Dictionary implements Map, Cloneable, Serializable  
example:
Hashtable hm=new Hashtable();

Methods of Java Hashtable class

Method Description
void clear() It is used to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Enumeration keys() It returns an enumeration of the keys in the hashtable.
Set keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V put(K key, V value) It inserts the specified value with the specified key in the hash table.
void putAll(Map t)) It is used to copy all the key-value pair from map to hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
String toString() It returns a string representation of the Hashtable object.
Collection values() It returns a collection view of the values contained in the map.
boolean contains(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and rehashes all of its keys.
V get(Object key) This method returns the object that contains the value associated with the key.
V remove(Object key) It is used to remove the key and its value. This method returns the value associated with the key.
int size() This method returns the number of entries in the hash table.

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given below.

HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

Java EnumSet class

Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.

EnumSet class declaration
public abstract class EnumSet> extends AbstractSet implements Cloneable, Serializ
example:

    import java.util.*;  
    enum days {  
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY  
    }  
    public class EnumSetExample {  
      public static void main(String[] args) {  
        Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);  
        // Traversing elements  
        Iterator iter = set.iterator();  
        while (iter.hasNext())  
          System.out.println(iter.next());  
      }  
    }


    import java.util.*;  
    enum days {  
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY  
    }  
    public class EnumSetExample {  
      public static void main(String[] args) {  
        Set set1 = EnumSet.allOf(days.class);  
          System.out.println("Week Days:"+set1);  
          Set set2 = EnumSet.noneOf(days.class);  
          System.out.println("Week Days:"+set2);     
      }  
    }  	

Java EnumMap class

Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum and AbstractMap classes.

EnumMap class declaration
public class EnumMap,V> extends AbstractMap implements Serializable, Cloneable
example:

       import java.util.*;  
    public class EnumMapExample {  
       // create an enum  
       public enum Days {  
       Monday, Tuesday, Wednesday, Thursday  
       };  
       public static void main(String[] args) {  
       //create and populate enum map  
       EnumMap map = new EnumMap(Days.class);  
       map.put(Days.Monday, "1");  
       map.put(Days.Tuesday, "2");  
       map.put(Days.Wednesday, "3");  
       map.put(Days.Thursday, "4");  
       // print the map  
       for(Map.Entry m:map.entrySet()){    
           System.out.println(m.getKey()+" "+m.getValue());    
          }   
       }  
    }  

Java Collections class

Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class.

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

The important points about Java Collections class are:

  • Java Collection class supports the polymorphic algorithms that operate on collections.
  • Java Collection class throws a NullPointerException if the collections or class objects provided to them are null.
Collections class declaration
public class Collections extends Object 

example:

    import java.util.*;  
    public class CollectionsExample {  
        public static void main(String a[]){      
            List list = new ArrayList();  
            list.add("C");  
            list.add("Core Java");  
            list.add("Advance Java");  
            System.out.println("Initial collection value:"+list);  
            Collections.addAll(list, "Servlet","JSP");  
            System.out.println("After adding elements collection value:"+list);  
            String[] strArr = {"C#", ".Net"};  
            Collections.addAll(list, strArr);  
            System.out.println("After adding array collection value:"+list);  
        }  
    }  

SN Modifier & Type Methods Descriptions
1) static boolean addAll() It is used to adds all of the specified elements to the specified collection.
2) static Queue asLifoQueue() It returns a view of a Deque as a Last-in-first-out (LIFO) Queue.
3) static int binarySearch() It searches the list for the specified object and returns their position in a sorted list.
4) static Collection checkedCollection() It is used to returns a dynamically typesafe view of the specified collection.
5) static List checkedList() It is used to returns a dynamically typesafe view of the specified list.
6) static Map checkedMap() It is used to returns a dynamically typesafe view of the specified map.
7) static NavigableMap checkedNavigableMap() It is used to returns a dynamically typesafe view of the specified navigable map.
8) static NavigableSet checkedNavigableSet() It is used to returns a dynamically typesafe view of the specified navigable set.
9) static Queue checkedQueue() It is used to returns a dynamically typesafe view of the specified queue.
10) static Set checkedSet() It is used to returns a dynamically typesafe view of the specified set.
11) static SortedMap checkedSortedMap() It is used to returns a dynamically typesafe view of the specified sorted map.
12) static SortedSet checkedSortedSet() It is used to returns a dynamically typesafe view of the specified sorted set.
13) static void copy() It is used to copy all the elements from one list into another list.
14) static boolean disjoint() It returns true if the two specified collections have no elements in common.
15) static Enumeration emptyEnumeration() It is used to get an enumeration that has no elements.
16) static Iterator emptyIterator() It is used to get an Iterator that has no elements.
17) static List emptyList() It is used to get a List that has no elements.
18) static ListIterator emptyListIterator() It is used to get a List Iterator that has no elements.
19) static Map emptyMap() It returns an empty map which is immutable.
20) static NavigableMap emptyNavigableMap() It returns an empty navigable map which is immutable.
21) static NavigableSet emptyNavigableSet() It is used to get an empty navigable set which is immutable in nature.
22) static Set emptySet() It is used to get the set that has no elements.
23) static SortedMap emptySortedMap() It returns an empty sorted map which is immutable.
24) static SortedSet emptySortedSet() It is used to get the sorted set that has no elements.
25) static Enumeration enumeration() It is used to get the enumeration over the specified collection.
26) static void fill() It is used to replace all of the elements of the specified list with the specified elements.
27) static int frequency() It is used to get the number of elements in the specified collection equal to the specified object.
28) static int indexOfSubList() It is used to get the starting position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
29) static int lastIndexOfSubList() It is used to get the starting position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
30) static ArrayList list() It is used to get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
31) static > T max() It is used to get the maximum value of the given collection, according to the natural ordering of its elements.
32) static > T min() It is used to get the minimum value of the given collection, according to the natural ordering of its elements.
33) static List nCopies() It is used to get an immutable list consisting of n copies of the specified object.
34) static Set newSetFromMap() It is used to return a set backed by the specified map.
35) static boolean replaceAll() It is used to replace all occurrences of one specified value in a list with the other specified value.
36) static void reverse() It is used to reverse the order of the elements in the specified list.
37) static Comparator reverseOrder() It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which implement the Comparable interface.
38) static void rotate() It is used to rotate the elements in the specified list by a given distance.
39) static void shuffle() It is used to randomly reorders the specified list elements using a default randomness.
40) static Set singleton() It is used to get an immutable set which contains only the specified object.
41) static List singletonList() It is used to get an immutable list which contains only the specified object.
42) static Map singletonMap() It is used to get an immutable map, mapping only the specified key to the specified value.
43) static >void sort() It is used to sort the elements presents in the specified list of collection in ascending order.
44) static void swap() It is used to swap the elements at the specified positions in the specified list.
45) static Collection synchronizedCollection() It is used to get a synchronized (thread-safe) collection backed by the specified collection.
46) static List synchronizedList() It is used to get a synchronized (thread-safe) collection backed by the specified list.
47) static Map synchronizedMap() It is used to get a synchronized (thread-safe) map backed by the specified map.
48) static NavigableMap synchronizedNavigableMap() It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map.
49) static NavigableSet synchronizedNavigableSet() It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set.
50) static Set synchronizedSet() It is used to get a synchronized (thread-safe) set backed by the specified set.
51) static SortedMap synchronizedSortedMap() It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map.
52) static SortedSet synchronizedSortedSet() It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set.
53) static Collection unmodifiableCollection() It is used to get an unmodifiable view of the specified collection.
54) static List unmodifiableList() It is used to get an unmodifiable view of the specified list.
55) static Map unmodifiableMap() It is used to get an unmodifiable view of the specified map.
56) static NavigableMap unmodifiableNavigableMap() It is used to get an unmodifiable view of the specified navigable map.
57) static NavigableSet unmodifiableNavigableSet() It is used to get an unmodifiable view of the specified navigable set.
58) static Set unmodifiableSet() It is used to get an unmodifiable view of the specified set.
59) static SortedMap unmodifiableSortedMap() It is used to get an unmodifiable view of the specified sorted map.
60 static SortedSet unmodifiableSortedSet() It is used to get an unmodifiable view of the specified sorted set.

Sorting in Collection

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

We can sort the elements of:

  • String objects
  • Wrapper class objects
  • User-defined class objects

Example:

Example to sort string objects
import java.util.*;  
class TestSort1{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
al.add("Viru");  
al.add("Saurav");  
al.add("Mukesh");  
al.add("Tahir");  
  
Collections.sort(al);  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
 }  
}  
}  
Example to sort string objects in reverse order
import java.util.*;  
class TestSort2{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
        al.add("Viru");    
        al.add("Saurav");    
        al.add("Mukesh");    
        al.add("Tahir");   
          
        Collections.sort(al,Collections.reverseOrder());  
        Iterator i=al.iterator();  
        while(i.hasNext())  
        {  
            System.out.println(i.next());  
        }  
}  
}  
Example to sort Wrapper class objects
import java.util.*;  
class TestSort3{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
al.add(Integer.valueOf(201));  
al.add(Integer.valueOf(101));  
al.add(230);//internally will be converted into objects as Integer.valueOf(230)  
  
Collections.sort(al);  
  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
 }  
}  
}  
Example to sort user-defined class objects
import java.util.*;  
  
class Student implements Comparable {  
    public String name;  
  public Student(String name) {  
    this.name = name;  
  }  
  public int compareTo(Student person) {  
    return name.compareTo(person.name);  
      
  }   
}  
public class TestSort4 {  
  public static void main(String[] args) {  
      ArrayList al=new ArrayList();  
      al.add(new Student("Viru"));  
      al.add(new Student("Saurav"));  
      al.add(new Student("Mukesh"));  
      al.add(new Student("Tahir"));  
      
    Collections.sort(al);  
    for (Student s : al) {  
      System.out.println(s.name);  
    }  
  }  
}  

Properties class in Java

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable. It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file

Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.

Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) It loads data from the Reader object.
public void load(InputStream is) It loads data from the InputStream object
public void loadFromXML(InputStream in) It is used to load all of the properties represented by the XML document on the specified input stream into this properties table.
public String getProperty(String key) It returns value based on the key.
public String getProperty(String key, String defaultValue) It searches for the property with the specified key.
public void setProperty(String key, String value) It calls the put method of Hashtable.
public void list(PrintStream out) It is used to print the property list out to the specified output stream.
public void list(PrintWriter out)) It is used to print the property list out to the specified output stream.
public Enumeration propertyNames()) It returns an enumeration of all the keys from the property list.
public Set stringPropertyNames() It returns a set of keys in from property list where the key and its corresponding value are strings.
public void store(Writer w, String comment) It writes the properties in the writer object.
public void store(OutputStream os, String comment) It writes the properties in the OutputStream object.
public void storeToXML(OutputStream os, String comment) It writes the properties in the writer object for generating XML document.
public void storeToXML(Writer w, String comment, String encoding) It writes the properties in the writer object for generating XML document with the specified encoding.

Example:

db.properties
user=system  
password=oracle 


Test.java
import java.util.*;  
import java.io.*;  
public class Test {  
public static void main(String[] args)throws Exception{  
    FileReader reader=new FileReader("db.properties");  
      
    Properties p=new Properties();  
    p.load(reader);  
      
    System.out.println(p.getProperty("user"));  
    System.out.println(p.getProperty("password"));  
}  
}   
mport java.util.*;  
import java.io.*;  
public class Test {  
public static void main(String[] args)throws Exception{  
  
Properties p=System.getProperties();  
Set set=p.entrySet();  
  
Iterator itr=set.iterator();  
while(itr.hasNext()){  
Map.Entry entry=(Map.Entry)itr.next();  
System.out.println(entry.getKey()+" = "+entry.getValue());  
}  
  
}  
}     
import java.util.*;  
import java.io.*;  
public class Test {  
public static void main(String[] args)throws Exception{  
  
Properties p=new Properties();  
p.setProperty("name","Sonoo Jaiswal");  
p.setProperty("email","sonoojaiswal@javatpoint.com");  
  
p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");  
  
}  
}      
bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States