Category Archives: Collections

Java: Collection Framework Introduction


A collection is an object (also called container) to deal with a group of objects or elements as a single unit. These objects called as elements of Collection. Collections are used to perform operations like the store, retrieve, manipulate, communicate and aggregate.

A collection can have a different type of data. Based on data can decide the type collection data structure.

  • Homogeneous
  • Heterogeneous
  • Unique
  • Duplicate

See Also: 

Real-life Example of Collection

Here are some real-life examples of collections:

  • LinkedList: Your web page visiting history.
  • LinkedList: Train Coaches are connected to each other.
  • LinkedList: Our brain, when we remember something memory follow association because of one memory link to another.  This way recall in sequence.
  • Stack & LinkedList: Stack of Plates or Towel at the party. The top plate always picks first.
  • Queue & LinkedList: Queue/line of the person standing on the railway ticket window or for food in the mess.
  • A classroom is a collection of students.
  • A money bank is a collection of coins.
  • A school bag is a collection of books.

Why need collection?

There are four ways in Java to store values by JVM.

1:Variable approach

If we need to handle one, two or three or fewer numbers of values then the variable approach is a good bit if need to deal with so many objects like 5000 then variable approach have some drawback:

  • The limitation of a variable is that it can store only one value at a time.
  • Readability and reusability of the code will be down.
  • JVM will take more time for the execution.

2: Using a class object approach

Using a class object, we can store multiple “fixed” numbers of values of different types. For example, suppose we are creating a class named Person.

class Person{
String Name ;
int age ;
}

If you create the object of Person class like this

Person p1=new Person(); // So can you think how many values can store in this person object?

The answer is only two i.e name and age. but if you will want to store the third value, it will not possible.

3: Using an array object approach

Array improved the readability of code, by using a single variable for a huge number of values but there are various problems and limitations with the array.


Student[] st=new Student[5000];
  1. Array allow to store only homogeneous data type.
  2. Array is static and fixed in length size.
  3. Array concept help with standard data structure, but when need to deal with the sorting of objects, search for a specific item, etc.

4: Collection Object:

By using a collection object, we can store the same or different data without any size limitation.

What is a Framework in Java?

A framework is a set of several classes and interfaces which provide a readymade architecture.

What is a Collections Framework?

A collection framework provides a unified readymade architecture for storing and manipulating a group of objects. All collections frameworks contain the following:

  • Interfaces: Interfaces generally forms a hierarchy and allow collections object to be manipulated independently of the details of their representation.
  • Implementations: Provides a concrete representation by data structure and implementation of  collections interfaces.
  • Algorithms: The methods that perform useful operations, such as searching and sorting, on objects that implement collection interfaces.

Benefits of Collections Framework

Collections Framework provides lots of benefits:

  • Reduces programming effort: The Collections framework provides useful data structures and algorithms so that developers can concentrate on programming logic only.
  • Increases program performance and quality: Collections Framework provides high-quality data structures and algorithms implementations for good performance. These collections interface APIs are interchangeable so that easily tuned by switching collection implementations.
  • Allows interoperability among unrelated APIs: These data structures are interchangeable so that choose data structure and algorithms according to requirement.
  • Reduces effort to learn and to use new APIs: Most of APIs are common for collections framework because of the inherent Collection interface. only some APIs need to remember that are specific to the data structure.
  • Reduces effort to design new APIs: If new data structure and algorithm change create polymorphism of API and change the internal algorithm of APIs.
  • Fosters software reuse: If new data structure added use standard APIs so that easy to learn for developers.

References

Java : Collection Framework Hierarchy


All the classes and interfaces of the collection framework are in java.util package. This hierarchy for the collection framework specifically mentioned the class and interface with respect to each type.

Java Collection Framework Hierarchy

Iterable Interface

The Iterable interface is the root interface for all the collection classes because the Collection interface extends the Iterable interface, therefore, all the subclasses of Collection interface also implement the Iterable interface.

The iterable interface contains only one abstract method.

  • Iterator iterator(): It returns the iterator over the elements of type T.

Iterator Interface

The iterator interface provides the facility of iterating the elements in a forward direction only.
For more detail: Java: Iterator Interface methods and Examples

Collection Interface

The Collection interface builds the foundation for the Collection framework. The collection interface is one of the interfaces which is implemented by all the Collection framework classes. It provides common methods to implement by all the subclasses of collection interfaces.
For more detail: Java: Collection Interface methods and Examples

List Interface

List interface is the subtype/child interface of the Collection interface. It stores objects/elements in list type data structure in ordered form and also allowed duplicate values.

Implementation classes for List interface are ArrayList, LinkedList, Vector, and Stack.

For Example: To instantiate List Interface with Implementation classes follow:


List  list1= new ArrayList();  
List  list2 = new LinkedList();  
List  list3 = new Vector();  
List  list4 = new Stack();

For more detail: Java: List Interface methods and Examples

ArrayList Class

The ArrayList implements the List interface. It’s having the following features:

  • ArrayList uses a dynamic array data structure to store objects and elements.
  • ArrayList allows duplicate objects and elements.
  • ArrayList maintains the insertion order.
  • ArrayList is non-synchronized.
  • ArrayList elements/objects can be accessed randomly.

For more detail: Java: ArrayList Interface methods and Examples

LinkedList Class

LinkedList implements the List interface. It’s having the following features:

  • LinkedList uses a doubly linked list data structure to store elements.
  • LinkedList allowed storing the duplicate elements.
  • LinkedList maintains the insertion order.
  • LinkedList is not synchronized.
  • LinkedList manipulation is fast because no shifting is required.

For more detail: Java: LinkedList Class methods and Examples

Vector Class

Vector Class implements List interface. It’s having the following features:

  • Vector is similar to the ArrayList class.
  • Vector class uses data structure as a dynamic array to store the data elements.
  • Vector is synchronized.
  • Vector contains many methods that are not the part of Collection Framework.

For more detail: Java: Vector Class methods and Examples

Stack Class

The Stack is the subclass of the Vector class. It’s having the following features:

  • Stack implements the Vector data structure with the (LIFO)last-in-first-out.
  • Stack contains all of the methods of the Vector class.
  • Stack also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its features.

For more detail: Java: Stack Class methods and Examples

Queue Interface

Queue Interface extends the Collection interface. It’s having the following features:

  • Queue interface maintains the FIFO (first-in-first-out) order.
  • Queue can be defined as an ordered list that is used to hold the elements which are about to be processed.
  • Queue interface implemented by the various classes like PriorityQueue, Deque, and ArrayDeque.

Queue interface can be instantiated as:

Queue q1 = new PriorityQueue();  
Queue q2 = new ArrayDeque();  

For more detail: Java: Queue Interface methods and Examples

Here are detail about classes which implements Queue Interface.

PriorityQueue

The PriorityQueue class implements the Queue interface.

  • PriorityQueue holds the elements or objects which are to be processed by their priorities.
    PriorityQueue doesn’t allow null values to be stored in the queue.

For more detail: Java: PriorityQueue Class methods and Examples

Deque Interface

Deque stands for the double-ended queue which allows us to perform the operations at both ends.interface extends the Queue interface.

  • Deque extends the Queue interface.
  • Deque allows remove and add the elements from both the side.
Deque d = new ArrayDeque(); 

For more detail: Java: Deque Interface methods and Examples

ArrayDeque Class

ArrayDeque class implements the Deque interface.

  • ArrayDeque facilitates us to use the Deque.
  • ArrayDeque allows add or delete the elements from both the ends.
  • ArrayDeque is faster than ArrayList and has no capacity restrictions.

For more detail: Java: ArrayQueue Class methods and Examples

Set Interface

Set Interface extends Collection Interface and present in java.util package.

  • Set doesn’t allow duplicate elements or objects.
  • Set store elements in an unordered way.
  • Set allows only one null value.
  • Set is implemented by HashSet, LinkedHashSet, and TreeSet.

We can create an instantiation of Set as below:

Set s1 = new HashSet();  
Set s2 = new LinkedHashSet();  
Set s3 = new TreeSet();

For more detail: Java: Set Interface methods and Examples

HashSet

HashSet class implements Set Interface. It’s having the following features:

  • HashSet internally uses data structure like a hash table for storage.
  • HashSet uses hashing technique for storage of the elements.
  • HashSet always contains unique items.

For more detail: Java: HashSet Class methods and Examples

LinkedHashSet

LinkedHashSet class implements Set Interface. It’s having the following features:

  • LinkedHashSet store items in LinkedList.
  • LinkedHashSet store unique elements.
  • LinkedHashSet maintains the insertion order.
  • LinkedHashSet allows null elements.

For more detail: Java: LinkedHashSet Class methods and Examples

SortedSet Interface

SortedSet Interface extends Set Interface. It’s having the following features:

  • SortedSet provides a total ordering on its elements.
  • SortedSet elements are arranged in the increasing (ascending) order.
  • SortedSet provides additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet set = new TreeSet();  

For more detail: Java: SortedSet Interface methods and Examples

TreeSet Class

TreeSet class implements the SortedSet interface.  It’s having the following features:

  • TreeSet uses a tree data structure for storage.
  • TreeSet also contains unique elements.
  • TreeSet elements access and retrieval time is quite fast.
  • TreeSet elements stored in ascending order.

For more detail: Java: TreeSet Class methods and Examples

Map Interface

In the collection framework, a map contains values on the basis of key and value pair. This pair is known as an entry. A map having the following features:

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for traversing needs to convert into the set using method keySet() or entrySet().

For more detail: Java: Map Class methods and Examples

HashMap Class

HashMap class implements Map interface. It’s having following features:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

For more detail:

LinkedHashMap Class

LinkedHashMap class extends the HashMap class. It’s having the following features:

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

For more detail: Java: LinkedHashMap Class methods and Examples

TreeMap Class

TreeMap class implements the SortedMap interface. it’s having the following features:

  • TreeMap uses data structure as red-black tree.
  • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • TreeMap contains only unique elements.
  • TreeMap doesn’t allow null keys and values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

For more detail: Java: TreeMap Class methods and Examples

HashTable Class

Hashtable class implements a Map interface and extends Dictionary class to store key and values as pairs. It’s having the following features:

  • HashTable store values as an array of the list where each list is known as a bucket of the node(key and value pair).
  • HashTable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

For more detail: Java: HashTable Class methods and Examples

See Also:

Java: Arrays vs Collections


In Java, Arrays and Collections both are to deal with a group of objects but there are lots of differences in terms of data structure or performing operations.

Here are some most common differences:

Difference between Arrays & Collections

Arrays Collections
Arrays is having fixed-length.. Collections are growable in nature i.e increase or decrease.
Arrays are not recommended in terms of memory concerns. Collections use different data structures and recommended to use with respect to memory.
Arrays are used with respect to performance. Collections are not recommended to use with respect to performance.
Arrays can store only homogeneous (same type) of data. Collections can hold both homogeneous and heterogeneous elements.
Arrays do not have a single API. Collections having big list of methods.
Arrays can work with primitives and object types. Collections can hold only objects but not with primitive. If you pass as primitive internally convert to object.
See Also: Array & Arrays Class Examples See Also: Collection Framework and Examples

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 hierarchy

The hierarchy of EnumSet class is given in the figure given below.
EnumSet

EnumSet class declaration

Let’s see the declaration for java.util.EnumSet class.

public abstract class EnumSet<E extends Enum> extends AbstractSet implements Cloneable, Serializable  

Methods of Java EnumSet Class

Method Description
static <E extends Enum> EnumSet allOf(Class elementType) It is used to create an enum set containing all of the elements in the specified element type.
static <E extends Enum> EnumSet copyOf(Collection c) It is used to create an enum set initialized from the specified collection.
static <E extends Enum> EnumSet noneOf(Class elementType) It is used to create an empty enum set with the specified element type.
static <E extends Enum> EnumSet of(E e) It is used to create an enum set initially containing the specified element.
static <E extends Enum> EnumSet range(E from, E to) It is used to create an enum set initially containing the specified elements.
EnumSet clone() It is used to return a copy of this set.

Example :EnumSet

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());
  }
}

Output :


TUESDAY
WEDNESDAY

Java EnumSet Example: allOf() and noneOf()

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);
  }
}

Output :


Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]

Java: ArrayList Vs Vector Class


java.util.ArrayList and java.util.Vector both implements List interface and maintains insertion order. It’s having many differences as below:

ArrayList vs Vector

ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increases 50% of the current array size if the number of elements exceeds its capacity. Vector increase 100% means doubles the array size when the total number of elements exceeds its capacity.
ArrayList is not a legacy class. It is introduced in JDK 1.2. Vector is a legacy class.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in the runnable or non-runnable state until the current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse the elements. A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
See Also:ArrayList Class See Also:Java: Vector Class

ArrayList Example: traversing by the iterator

import java.util.*;
class ArrayListExample{
 public static void main(String args[]){    

  //creating arraylist of String
  List al=new ArrayList();
 //adding objecta in arraylist
  al.add("Saurabh");
  al.add("Mahesh");
  al.add("Jonny");
  al.add("Anil");
  //traverse elements using Iterator
  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

Output

Saurabh
Mahesh
Jonny
Anil

Vector Example: Traversing by Enumerator

import java.util.*;
class VectorExample{
 public static void main(String args[]){
  Vector v=new Vector();//creating vector
  v.add("Umrao");//method of Collection
  v.addElement("Isha");//method of Vector
  v.addElement("Kush");
  //traverse elements using Enumeration
  Enumeration e=v.elements();
  while(e.hasMoreElements()){
   System.out.println(e.nextElement());
  }
 }
}

Output

Umrao
Isha
Kush

Java: How HashSet Work?


A Set interface represents a group of unique elements arranged like an array. When we try to pass the duplicate element that is already available in the Set, then it will not store into the Set.

HashSet class

HashSet class implemnets Set interface and extends AbstractSet class.A HashSet class uses Hash Map internally for storing elements by using hashing technique.HashSet store unique elements and does not guarantee the order of elements.

Suppose, you want to create a HashSet to store a group of Strings, then create the HashSet object as:


HashSet hs=new HashSet();  

Where is the generic type parameter to represent HashSet allows only String type objects.

HashSet default constructor create instance of initial capacity 16 and capacity may increase automatically when number of elements reach to load factors. For uniqueness of object generate key as hashcode value. HashSet class doesn’t have method to retrieve object of Instance only way is retrieve object by iteration.

Note: To set your own capacity and loadfactor for HashSet. you can use below constructor.


HashSet hs=new HashSet(int capacity, float loadfactor);  

Here, loadfactor determines when number of elements in HashSet reach to that capacity limit increase capacity internally.the point where the capacity of HashSet would be increased internally.
The initial default capacity of HashSet is 16. The default load factor is 0.75. then 16*0.75=12 when no of elements reach to 12 increase capacity of HashSet to store more elements.

Example HashSet:

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample1 {
	public static void main(String[] args) {
      HashSet countries=new HashSet();
      countries.add("India");
      countries.add("Pakistan");
      countries.add("China");
      countries.add("Nepal");
      countries.add("Afganistan");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Thailand");
      countries.add("Malasia");
      countries.add("Russia");
      countries.add("London");
      countries.add("Switzerand");
      //Till that point threshold/capacity value is 12
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());
      //Duplicate elements not allowed
      System.out.println("Add Dubai:"+countries.add("Dubai"));
      System.out.println("Add Dubai :"+countries.add("Dubai"));//return false when duplicate
      //After adding 13th element Threshold/capacity reach to 24 just double
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());

     //iteration of Hashset elements
      System.out.println("\n\nPrint Countries by for each:");
      for(String country:countries)
      {
    	 System.out.println(country);
      }

      System.out.println("\n\nPrint Countries by for iterator:");
      Iterator it=countries.iterator();
      while(it.hasNext())
      {
    	  System.out.println(it.next());
      }

	}
}

Output


Countries Name:[Canada, Pakistan, China, Malasia, Brazil, London, Afganistan, Thailand, Nepal, Switzerand, India, Russia]
Total Countries:12
Add Dubai:true
Add Dubai :false
Countries Name:[Malasia, Thailand, Dubai, India, Russia, Canada, Pakistan, China, Brazil, London, Afganistan, Nepal, Switzerand]
Total Countries:13


Print Countries by for each:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand


Print Countries by for iterator:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand

In this example we have added duplicate values as Dubai in HashSet. When added it first time by add method return true because Dubai was not in HashSet. When added again return false because it was already added.

How HashSet work?

Now question comes how HashSet, add() method returns true and false. When you will open HashSet implementation of the add() method in Java APIs i.e. rt.jar, you will see the following code in it:

public class HashSet&ltE> extends AbstractSet
{
private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet()
{
map = new HashMap();
}
public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}
}

In this HashSet, add(object) methods use HashMap delegated to put(key, value) internally. Where key is the object added on HashSet and value is constant object as PRESENT in java.util.HashSet.

When we create HashSet Object, internally create an object of HashMap. As we know in HashMap each key is unique so, When we call add(E e) method this passing object set as key of HashMap and dummy object (new Object()) which is referred by Object reference PRESENT pass as value.

In HashMap put(key, value):

  • If the Key is unique and added then it will return null
    If the Key is duplicate, then map will return the old value of the key.

Let consider above example, when add country as countries.add(“Dubai”), java internally call HashMap put(“Dubai”,PRESENT) method to add element in map.

public boolean add(E e)
{
return map.put(e, PRESENT==null);
}

If the method map.put(key, value) returns null, then the method map.put(e, PRESENT)==null will return true internally, and the element added to the HashSet.
If the method map.put(key, value) returns the old value of the key, then the method map.put(e, PRESENT)==null will return false internally, and the element will not add to the HashSet.

As per given implementation when country “Dubai” added first time put() method return as null because “Dubai” not added before (unique) then add method return true. But when “Dubai” added again put() method will return old object and add method will return false on that case because of duplicate.

Retrieving Object from the HashSet

We use iterator() method of HashSet to retrieve objects. Internally HashSet iterator method called map.keySet().iterator() method.

public Iterator iterator()
{
return map.keySet().iterator();
}

Java: Collections Class Methods and Examples


java.util.Collections class extends Object class. Collections also called as utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collection class supports polymorphic to operate on collections.
  • Collection class throws a NullPointerException if passing objects are null.

Collections Declaration

public class Collections extends Object 

Collections Class Methods

Methods Descriptions
static boolean addAll() Adds all of the specified elements to the given collection.
static Queue asLifoQueue() Returns a view of a Deque as a LIFO(Last in first out) Queue.
static int binarySearch() Searches the list for the specified object and returns their index position in a sorted list.
static Collection checkedCollection() Returns a dynamically type safe view of the given collection.
static List checkedList() Returns a dynamically type safe view of the given list.
static Map checkedMap() Returns a dynamically type safe view of the given map.
static NavigableMap checkedNavigableMap() Returns a dynamically type safe view of the given navigable map.
static NavigableSet checkedNavigableSet() Returns a dynamically type safe view of the given navigable set.
static Queue checkedQueue() Returns a dynamically type safe view of the given queue.
static Set checkedSet() Returns a dynamically type safe view of the given set.
static SortedMap checkedSortedMap() Returns a dynamically type safe view of the given sorted map.
static SortedSet checkedSortedSet() Returns a dynamically type safe view of the given sorted set.
static void copy() Copy all the elements from one list into a another list.
static boolean disjoint() Returns true if the two specified collections have no common elements.
static Enumeration emptyEnumeration() Get an enumeration that has no elements.
static Iterator emptyIterator() Get an Iterator that has no elements.
static List emptyList() Get a List that has no elements.
static ListIterator emptyListIterator() Get a List Iterator that has no elements.
static Map emptyMap() Returns an empty map which is immutable.
static NavigableMap emptyNavigableMap() Returns an empty navigable map which is immutable.
static NavigableSet emptyNavigableSet() Get an empty navigable set which is immutable in nature.
static Set emptySet() Get the set that has no elements.
static SortedMap emptySortedMap() Returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() Get the sorted set that has no elements.
static Enumeration enumeration() Get the enumeration over the specified collection.
static void fill() Replace all of the elements of the specified list with the specified elements.
static int frequency() Get the number of elements in the specified collection equal to the given object.
static int indexOfSubList() Get the starting index position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static int lastIndexOfSubList() Get the starting index position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static ArrayList list() Get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
static > T max() Get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() Get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() Get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() Return a set backed by the specified map.
static boolean replaceAll() Replace all occurrences of one specified value in a list with the other specified value.
static void reverse() Reverse the order of the elements in the given list.
static Comparator reverseOrder() Get the comparator that imposes the reverse of the natural ordering of elements on a collection of objects which implement the Comparable interface.
static void rotate() Rotate the elements in the specified list by a given distance.
static void shuffle() Randomly reorders the specified list elements using a default randomness.
static Set singleton() Get an immutable set which contains only the specified object.
static List singletonList() Get an immutable list which contains only the specified object.
static Map singletonMap() Get an immutable map, mapping only the specified key to the specified value.
static >void sort() Sort the elements presents in the specified list of collection in ascending order.
static void swap() Swap the elements at the specified positions in the given list.
static Collection synchronizedCollection() Get a synchronized (thread-safe) collection backed by the given collection.
static List synchronizedList() Get a synchronized (thread-safe) collection backed by the given list.
static Map synchronizedMap() Get a synchronized (thread-safe) map backed by the given map.
static NavigableMap synchronizedNavigableMap() Get a synchronized (thread-safe) navigable map backed by the given navigable map.
static NavigableSet synchronizedNavigableSet() Get a synchronized (thread-safe) navigable set backed by the given navigable set.
static Set synchronizedSet() Get a synchronized (thread-safe) set backed by the given set.
static SortedMap synchronizedSortedMap() Get a synchronized (thread-safe) sorted map backed by the given sorted map.
static SortedSet synchronizedSortedSet() Get a synchronized (thread-safe) sorted set backed by the given sorted set.
static Collection unmodifiableCollection() Get an unmodifiable view of the given collection.
static List unmodifiableList() Get an unmodifiable view of the given list.
static Map unmodifiableMap() Get an unmodifiable view of the given map.
static NavigableMap unmodifiableNavigableMap() Get an unmodifiable view of the given navigable map.
static NavigableSet unmodifiableNavigableSet() Get an unmodifiable view of the given navigable set.
static Set unmodifiableSet() Get an unmodifiable view of the given set.
static SortedMap unmodifiableSortedMap() Get an unmodifiable view of the given sorted map.
static SortedSet unmodifiableSortedSet() Get an unmodifiable view of the given sorted set.

Collections Example : Add elements in list

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample3 {
	public static void main(String a[]) {
		Listlist = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: EnumMap Class Methods and Examples


java.util.EnumMap class inherits Enum and AbstractMap classes. It’s special type of Map for enum keys.

EnumMap Declaration

public class EnumMap,V> extends AbstractMap implements Serializable, Cloneable  
  • K: Represent as key in Map of type Enum
  • V:Represent as value with respect to K.

Constructors of EnumMap

Constructor Description
EnumMap(Class keyType) Create an empty enum map with the given key type.
EnumMap(EnumMap m) Create an enum map with the same key type as the given enum map.
EnumMap(Map m) Create an enum map initialized from the given map.

Methods of EnumMap

Method Description
clear() Clear all the mapping from the map.
clone() Copy the mapped value of one map to another map as sallow cloning.
containsKey() Check whether a given key is present in this map or not.
containsValue() Check whether one or more key is associated with a specified value or not.
entrySet() Create a set of keys/elements contained in the EnumMap.
equals() Compare two maps keys for equality.
get() Get the mapped value with respect to given key.
hashCode() Get the hashcode value of the EnumMap.
keySet() Return the set of the keys contained in the map.
size() Get count of the size of the EnumMap.
Values() Create a collection view of the values contained in this map.
put() Associate the given value with the specified key in this EnumMap.
putAll() Copy all the mappings from one EnumMap to another new EnumMap.
remove() Remove the mapping for the given key from EnumMap if the given key exist in EnumMap.

EnumMap Example : insert elements and traverse

import java.util.*;

public class EnumMapExample1 {
	// create an enum for keys
	public enum Days {
		Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
	};

	public static void main(String[] args) {

		// Insert elements in map
		EnumMap map = new EnumMap(Days.class);
		map.put(Days.Monday, "1");
		map.put(Days.Wednesday, "3");
		map.put(Days.Friday, "5");
		map.put(Days.Sunday, "7");
		// traverse map
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Monday 1
Wednesday 3
Friday 5
Sunday 7

EnumMap Example: insert objects and traverse

import java.util.EnumMap;
import java.util.Map;
class Magzine {
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class EnumMapWithObjectsExample {
	// Creating enum of keys
	public enum Key {
		One, Two, Three
	};

	public static void main(String[]args){
EnumMap map = new EnumMap(Key.class);
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzines to Map
		map.put(Key.One, m1);
		map.put(Key.Two, m2);
		map.put(Key.Three, m3);
		// Traversing EnumMap
		for (Map.Entry entry : map.entrySet()) {
			Magzine m = entry.getValue();
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


21 The Sun Sy Sunfranchy The Sun Company 8
22 Glimmer Trains Unknown Glimmer Train Press 4
23 Crazy horse Brett Lot College of Charleston 6

Java: Map Interface Methods and Examples


In the collection framework, a map contains values on the basis of key and value pairs. This pair is known as an entry.

Points to Remember

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in the Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for transversing needs to convert into the set using method keySet() or entrySet().

See Also:

Methods of Map Interface

Method Description
put(Object key, Object value) This method used to insert an entry on the map.
void putAll(Map map) This method inserts the specified map in the map.
V putIfAbsent(K key, V value) This method inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) This method used to delete an entry for the specified key.
boolean remove(Object key, Object value) This method removes the specified values with the associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
V compute(K key, BiFunction remappingFunction) This method computes 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) This method computes 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) This method computes 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)  if some value equal to the value exists within the map then return true, else return false.
boolean containsKey(Object key) if some key equal to the key exists within the map return true, else return false.
boolean equals(Object o) It is used to compare the specified Object values with the Map.
void forEach(BiConsumer action) Mentioned action will perform for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) Returns the object that contains the value with respect to the key.
V getOrDefault(Object key, V defaultValue) Returns the value with respect to 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
boolean isEmpty() Check if the map not having any element Returns true if the map is empty or false.
V merge(K key, V value, BiFunction remappingFunction) If the given key is not mapped with a value or with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to the key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to the key.
void replaceAll(BiFunction function) It replaces each entry’s value with the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() Returns the number of elements in the map.

Map.Entry Interface

Entry is the subinterface of Map. So we will be accessed by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.

Methods of Map.Entry interface

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the other existing objects.
static ,V> Comparator<Map.Entry> comparingByKey() It returns a comparator that compare the objects in natural order on key.
static Comparator<Map.Entry> comparingByKey(Comparator cmp) It returns a comparator that compare the objects by key using the given Comparator.
static <K,V extends Comparable> Comparator<Map.Entry> comparingByValue() It returns a comparator that compare the objects in natural order on value.
static Comparator<Map.Entry> comparingByValue(Comparator cmp) It returns a comparator that compare the objects by value using the given Comparator.

Map Example: Legacy Style without Generics

import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
    Map map=new HashMap();
    //Adding elements to map
    map.put(1,"Anuj");
    map.put(5,"Raghav");
    map.put(2,"Jitendra");
    map.put(3,"Anuj");
    //Traversing Map Entry
	//Converting to Set so that we can traverse
    Set set=map.entrySet();
    Iterator itr=set.iterator();
    while(itr.hasNext()){
        //Type cast to Map.Entry so that we can get key and value separately
        Map.Entry entry=(Map.Entry)itr.next();
        System.out.println(entry.getKey()+" "+entry.getValue());
    }
}
}

Output :


1 Anuj
2 Jitendra
5 Raghav
3 Anuj

Map Example: With Generics

import java.util.*;
class MapExample2{
 public static void main(String args[]){
  Map map=new HashMap();
  map.put(20,"Anuj");
  map.put(21,"Virendra");
  map.put(22,"Raghav");
  //Elements can traverse in any order
  for(Map.Entry m:map.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

Output :


22 Raghav
20 Anuj
21 Virendra

Map Example: comparingByKey() in ascending and descending order

import java.util.*;
class MapExample3{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav"); 

	  //ascending order
      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending oder
	  //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
      //Performs an action for each element of this stream
      .forEach(System.out::println);
 }
}

Output :


20=Anuj
21=Virendra
22=Raghav

Map Example: comparingByValue() in ascending and descending Order

import java.uti
class MapExample5{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav");  

	  //ascending order 

      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByValue())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending order

	  //Returns a Set view of the mappings contained in this map
     map.entrySet()
     //Returns a sequential Stream with this collection as its source
     .stream()
     //Sorted according to the provided Comparator
     .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
     //Performs an action for each element of this stream
     .forEach(System.out::println);
 }
}

Output :


20=Anuj
22=Raghav
21=Virendra

21=Virendra
22=Raghav
20=Anuj

Java: TreeMap Class Methods and Examples


Java.util.TreeMap implements SortedMap interface and provides an efficient way to storing key-value pairs in sorted order. TreeMap implements the NavigableMap interface and extends AbstractMap class.

Points to Remember

  • TreeMap uses data structure as a red-black tree.
  • TreeMap contains values based on the key.
  • TreeMap contains only unique elements.
  • TreeMap cannot have a null key but can have multiple null values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

TreeMap Declaration

public class TreeMap extends AbstractMap implements NavigableMap, Serializable,Cloneable
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

See Also:

What is the difference between HashMap and TreeMap?

HashMap TreeMap
HashMap can contain one null key. TreeMap cannot contain any null key.
HashMap maintains no order. TreeMap maintains an ascending order.

Constructors of TreeMap

Constructor Description
TreeMap() This constructor uses to create an empty treemap that will be sorted using the natural order of its key.
TreeMap(Comparator comparator) This constructor uses to an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap m) This constructor uses to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of TreeMap

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() This method 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 mention action for each entry in the map until all entries 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 map contains a mapping for the specified key.
Set keySet() It returns the set 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 and value mapping associated with the greatest key less than the given key or null if there is no such key.
K lowerKey(K key) It returns from map  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 contains 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 and 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 respect to 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 value with respect to key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the mentioned function on all entries have been processed or the function throw an exception.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key and value pairs whose keys match with in range fromKey to toKey.
SortedMap subMap(K fromKey, K toKey) It returns key and value pairs whose keys range match fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(K fromKey) It returns key and value pairs whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive) It returns key and value pairs whose keys are greater than (o equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping with respect to  key.
boolean containsValue(Object value) It returns true if the map find one or more keys to the specified value.
K firstKey() It is used to return the first find 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 and value pair of the specified key from the map.
Set entrySet() It returns a set of the mappings contained in the map.
int size() It returns the number of key-value pairs that exists in the hashtable.
Collection values() It returns a collection  of values contained in the map.

TreeMap Example : insert and traverse elements

import java.util.Map;
import java.util.TreeMap;

class TreeMapExample1{
	 public static void main(String args[]){
	   TreeMap&lt;Integer,String&gt; map=new TreeMap&lt;Integer,String&gt;();
	      map.put(20,"Anuj");
	      map.put(22,"Ravi");
	      map.put(21,"Virendra");
	      map.put(23,"Raghav");    

	      for(Map.Entry m:map.entrySet()){
	       System.out.println(m.getKey()+" "+m.getValue());
	      }
	 }
	}

Output :


20 Anuj
21 Virendra
22 Ravi
23 Raghav

TreeMap Example : remove() elements

import java.util.*;

public class TreeMapExample2 {
	public static void main(String args[]) {
		TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("\nBefore invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		map.remove(22);
		System.out.println("\nAfter invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :



Before invoking remove() method
20 Anuj
21 Virendra
22 Ravi
23 Raghav

After invoking remove() method
20 Anuj
21 Virendra
23 Raghav

Treemap Example : with NavigableMap

import java.util.*;
import java.util.NavigableMap;
import java.util.TreeMap;

class TreeMapExample3 {
	public static void main(String args[]) {
		NavigableMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");

		// Maintains descending order
		System.out.println("\ndescendingMap: " + map.descendingMap());
		// Returns key-value pairs whose keys are less than or equal to the
		// specified key.
		System.out.println("\nheadMap: " + map.headMap(22, true));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22, true));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, false, 22, true));
	}
}

Output :


descendingMap: {23=Raghav, 22=Ravi, 21=Virendra, 20=Anuj}

headMap: {20=Anuj, 21=Virendra, 22=Ravi}

tailMap: {22=Ravi, 23=Raghav}

subMap: {21=Virendra, 22=Ravi}

TreeMap Example : SortedMap()

import java.util.*;
import java.util.SortedMap;
import java.util.TreeMap;

class TreeMapExample4 {
	public static void main(String args[]) {
		SortedMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Returns key-value pairs whose keys are less than the specified key.
		System.out.println("\nheadMap: " + map.headMap(22));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, 22));
	}
}

Output :


headMap: {20=Anuj, 21=Virendra}

tailMap: {22=Ravi, 23=Raghav}

subMap: {20=Anuj, 21=Virendra}

TreeMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
import java.util.Map;
import java.util.TreeMap;

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map&lt;Integer, Magzine&gt; table = new TreeMap&lt;Integer, Magzine&gt;();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry&lt;Integer, Magzine&gt; entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

 

Java: Collections Utility Class Methods and Examples


java.util.Collections class inherits Object class. The Collections utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collections class supports the polymorphic to operate on collections.
  • Collections class throws a NullPointerException if passing objects are null.

See Also:

Collections Declaration

public class Collections extends Object 

Collections Utility Class Methods

Method Descriptions
static boolean addAll() It is used to adds all of the specified element to the specified collection.
static Queue asLifoQueue() It returns a view of a Deque as a Last-in-first-out (LIFO) Queue.
static int binarySearch() It searches the list for the specified object and returns its position in a sorted list.
static Collection checkedCollection() It is used to returns a dynamically typesafe view of the specified collection.
static List checkedList() It is used to returns a dynamically typesafe view of the specified list.
static Map checkedMap() It is used to returns a dynamically typesafe view of the specified map.
static NavigableMap checkedNavigableMap() It is used to returns a dynamically typesafe view of the specified navigable map.
static NavigableSet checkedNavigableSet() It is used to returns a dynamically typesafe view of the specified navigable set.
static Queue checkedQueue() It is used to returns a dynamically typesafe view of the specified queue.
static Set checkedSet() It is used to returns a dynamically typesafe view of the specified set.
static SortedMap checkedSortedMap() It is used to returns a dynamically typesafe view of the specified sorted map.
static SortedSet checkedSortedSet() It is used to returns a dynamically typesafe view of the specified sorted set.
static void copy() It is used to copy all the elements from one list into another list.
static boolean disjoint() It returns true if the two specified collections have no elements in common.
static Enumeration emptyEnumeration() It is used to get an enumeration that has no elements.
static Iterator emptyIterator() It is used to get an Iterator that has no elements.
static List emptyList() It is used to get a List that has no elements.
static ListIterator emptyListIterator() It is used to get a List Iterator that has no elements.
static Map emptyMap() It returns an empty map that is immutable.
static NavigableMap emptyNavigableMap() It returns an empty navigable map that is immutable.
static NavigableSet emptyNavigableSet() It is used to get an empty navigable set which is immutable in nature.
static Set emptySet() It is used to get the set that has no elements.
static SortedMap emptySortedMap() It returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() It is used to get the sorted set that has no elements.
static Enumeration enumeration() It is used to get the enumeration over the specified collection.
static void fill() It is used to replace all of the elements of the specified list with the specified elements.
static int frequency() It is used to get the number of elements in the specified collection equal to the specified object.
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.
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.
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.
static > T max() It is used to get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() It is used to get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() It is used to get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() It is used to return a set backed by the specified map.
static boolean replaceAll() It is used to replace all occurrences of one specified value in a list with the other specified value.
static void reverse() It is used to reverse the order of the elements in the specified list.
static Comparator reverseOrder() It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which internally implement the Comparable interface.
static void rotate() It is used to rotate the elements in the specified list by a given distance.
static void shuffle() It is used to randomly reorders the specified list elements using default randomness.
static Set singleton() It is used to get an immutable set that contains only the specified object.
static List singletonList() It is used to get an immutable list that contains only the specified object.
static Map singletonMap() Use to get an immutable map, mapping only the specified key to the specified value.
static >void sort() It is used to sort the elements present in the specified list of the collection in ascending order.
static void swap() It is used to swap the elements at the specified positions in the specified list.
static Collection synchronizedCollection() It is used to get a synchronized (thread-safe) collection backed by the specified collection.
static List synchronizedList() It is used to get a synchronized (thread-safe) collection backed by the specified list.
static Map synchronizedMap() It is used to get a synchronized (thread-safe) map backed by the specified map.
static NavigableMap synchronizedNavigableMap() It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map.
static NavigableSet synchronizedNavigableSet() It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set.
static Set synchronizedSet() It is used to get a synchronized (thread-safe) set backed by the specified set.
static SortedMap synchronizedSortedMap() It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map.
static SortedSet synchronizedSortedSet() It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set.
static Collection unmodifiableCollection() It is used to get an unmodifiable view of the specified collection.
static List unmodifiableList() It is used to get an unmodifiable view of the specified list.
static Map unmodifiableMap() It is used to get an unmodifiable view of the specified map.
static NavigableMap unmodifiableNavigableMap() It is used to get an unmodifiable view of the specified navigable map.
static NavigableSet unmodifiableNavigableSet() It is used to get an unmodifiable view of the specified navigable set.
static Set unmodifiableSet() It is used to get an unmodifiable view of the specified set.
static SortedMap unmodifiableSortedMap() It is used to get an unmodifiable view of the specified sorted map.
static SortedSet unmodifiableSortedSet() It is used to get an unmodifiable view of the specified sorted set.

See Also:

Collections Example : Add elements in list

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample3 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: LinkedHashMap Class Methods and Examples


LinkedHashMap class extends the HashMap class and implements Map Interface to store values in key and value pairs.

Points to Remember

  • LinkedHashMap class is in java.util package.
  • LinkedHashMap uses data structure Hashtable and LinkedList implementation of the Map interface.
  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap class may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap initial default capacity is 16 with a load factor of 0.75.

LinkedHashMap Declaration


public class LinkedHashMap extends HashMap implements Map  
  • K: Here K represent Key of Map
  • V: Here V represents value in the Map with respect to K.

Constructors of LinkedHashMap class

Constructor Description
LinkedHashMap() This is the default LinkedHashMap constructor.
LinkedHashMap(int capacity)  Use to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor) Use to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) Use to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map m) Use to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of LinkedHashMap class

Method Description
V get(Object key) It returns the value object map to the specified key.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if one or more keys to the specified value.
Set<Map.Entry> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer action) It performs the given action on each entry in the map until all entries have been processed or any 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 in map 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.

LinkedHashMap Example : insert items and traverse

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample4 {

	public static void main(String args[]) {

		Map hm = new LinkedHashMap();

		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}

}

Output :


20 Anuj
21 Virendra
22 Raghav

LinkedHashMap Example : Key-Value pair

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample1 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		// Fetching key from LinkedHashMap
		System.out.println("Keys: " + map.keySet());
		// Fetching value from LinkedHashMap
		System.out.println("Values: " + map.values());
		// Fetching key-value pair from LinkedHashMap
		System.out.println("Key-Value pairs: " + map.entrySet());
	}

}

Output :


Keys: [20, 21, 22]
Values: [Anuj, Virendra, Raghav]
Key-Value pairs: [20=Anuj, 21=Virendra, 22=Raghav]

LinkedHashMap Example : remove()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample2 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {20=Anuj, 22=Ravi, 21=Virendra, 23=Raghav}
After remove: {20=Anuj, 21=Virendra, 23=Raghav}

LinkedHashMap Example : getOrDefault()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample3 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

LinkedHashMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
public class LinkedHashMapExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map map = new LinkedHashMap();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		map.put(1, m1);
		map.put(2, m2);
		map.put(3, m3);
		// Traversing map
		for (Map.Entry entry : map.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Java: HashTable Class Methods and Examples


The hashtable class implements a Map interface and extends Dictionary Class to store key and values as pairs.

Hashtable is an array of the list where each list is known as a bucket of the node (key and value pair). The position of the node is identified by calling the hashcode() method on key.

Points to remember

  • Hashtable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

See Also:

Hashtable class declaration

Let’s see the declaration for java.util.Hashtable class.


public class Hashtable extends Dictionary implements Map, Cloneable, Serializable  
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

Constructors of java.util.Hashtable class

Constructor Description
Hashtable() It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains a specified initial capacity.
Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map t) It creates a new hash table with the same mappings as the given Map.

Methods of java.util.Hashtable class

Method Description
void clear() Use 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<Map.Entry> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the 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) This method 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() This method 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 found in hashTable then 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 pairs from the map to the hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) in Hashtable then insert key and 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) This method replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) This method replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) This method 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 returns 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 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.

HashTable Example : add() key and value

import java.util.*;

public class HashTableExample1 {

	public static void main(String args[]) {
		Hashtable hm = new Hashtable();

		//add values in hash table
		hm.put(20, "Anuj");
		hm.put(22, "Ravi");
		hm.put(21, "Virendra");
		hm.put(23, "Raghav");

		//print all values from HashTable
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


21 Virendra
20 Anuj
23 Raghav
22 Ravi

HashTable Example : remove()

import java.util.Hashtable;

public class HashTableExample2 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
After remove: {21=Virendra, 20=Anuj, 23=Raghav}

Hashtable Example : getOrDefault()

import java.util.Hashtable;

public class HashTableExample3 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

Hashtable Example : putAbsent()

import java.util.*;
class HashtableExample4{
 public static void main(String args[]){
   Hashtable map=new Hashtable();
     map.put(20,"Anuj");
     map.put(22,"Ravi");
     map.put(21,"Virendra");
     map.put(23,"Raghav");
     System.out.println("Initial Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(24,"Gaurav");
     System.out.println("Updated Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(21,"Virendra");
     System.out.println("Updated Map: "+map);
 }
}

Output :


Initial Map: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}

Hashtable Example : with Objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map table = new Hashtable();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Java: Hashmap Working


What is Hashing?

Hashing is technique of converting an object into an integer value. For example hashcode() method always return int value. We can also override hashcode() method and implement own logic to get hashcode value.

Note : The integer value helps in indexing and faster searches.

What is HashMap

HashMap is a one type of collection in Java collection framework to store values in key and value pair. HashMap uses hashing technique for storing values. HashMap uses internal data structure as array and LinkedList for storing key and values. HashMap contains an array of nodes, and node presented by a class with respect to key.

See Also : Java: HashMap Class Methods and Examples

Contract between equals() and hashcode() method

Before discussing internal working of HashMap, need to understand hashCode() and equals() method contract in detail.

  • equals(): it’s Object class method to check the equality of two objects by comparing key, whether they are equal or not. It can be overridden.
  • hashCode(): it’s also object class methods which return memory reference of object in integer form. This value received from the hashcode() method is used as the bucket number or address of element inside Map. Hashcode value of null Key is 0.

If you override the equals() method, then it is mandatory to override the hashCod() method.

See Also: Java : java.lang.Object Class & Methods

Buckets: is an Array of the node, where each node has a data structure like a LinkedList. More than one node can use same bucket and may be different in capacity.

Working of HashMap

Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap. The default capacity of HashMap is 16 (0 to 15).

Example: In the following example, we want to insert six (Key, Value) pair in the HashMap.

HashMap map = new HashMap();
map.put("Ankur", 35);
map.put("Saurabh", 36);
map.put("Gaurav", 32);
map.put("Raghav", 29);
map.put("Rajendra", 40);
map.put("Shailesh", 33);

When we call the put() method, then it calculates the hash code of the Key i.e “Ankur” hashcode is 63412443. Now to store the Key and value pair in memory, we have to calculate the index based on below formulae.

HashMap Representataion.jpg

Calculating Index Formulae:


Index = hashcode(Key) & (n-1)  
Where n is the size of the array.

Hence the index value for Ankur and others are as below:
Calculate Index for “Ankur”
Index = 63412443& (16-1) = 11
Calculate Index for “Saurabh”
Index = -758033668& (16-1) = 12
Calculate Index for “Gaurav”
Index = 2125849484& (16-1) = 12
Calculate Index for “Raghav”
Index = -1854623835& (16-1) = 5
Calculate Index for “Rajendra”
Index = 201412911& (16-1) = 15
Calculate Index for “Shailesh”
Index = -687212437& (16-1) = 11

The key “Ankur” calculated index value is 11. This key and value pair store in one of the node of HashMap.

Hash Collision

Hash Collisions occured when two or more keys are calculating index as same value.

From above calculated index value, keys “Ankur and “Shailesh” both index value is 11 having hash collision. Similarly for “Saurabh” and “Gaurav” having index value 12. In this case, equals() method compare both Keys are equal or not. If Keys are equal, replace the value with the current value. Otherwise, linked this node object (key and value pair) to the existing node object through the LinkedList.

Similarly, we will store the other keys with respect to below index positions.

HashMap get() method to retrieve values

HashMap get(Key) method is used to retrieve value by Key. This method calculate index position based on key hashcode value and capacity of hashmap and fetch result. If no matching key find out will return result as value null.

Suppose we have to fetch the Key “Ankur.” The following method will be called.


map.get(new Key("Ankur"));

It generates the hash code as 63412443. Now calculate the index value of 63412443 by using index formula. The index value will be 11. get() method search for the index value 11. It compares the given key value sequentially in bucket with respect to index position 11. If any equal key find out in bucket will return value object with respect to that key otherwise finally return null if not no match find out.

Let’s fetch another Key “Raghav.” The hash code of the Key “Raghav” is -1854623835. The calculated index value of -1854623835 is 5. Go to index 5 of the array and compare the first element’s Key with the given Key “Raghav”. It return the value object for match key.

Java: HashMap Class Methods and Examples


java.util.HashMap class inherits AbstractMap class and implements the Map interface. HashMap values store on the basis of key and value pair where each pair is known as an Entry.

  • K: It’s the type of Key in HashMap
  • V: It’s a type of value with respect to Key.

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

HashMap Representataion

Difference between HashSet and HashMap

HashSet Class contains only values whereas HashMap Class contains an entry (key and value pair).

HashMap Class Constructors

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

HashMap Class Methods

Method Description
void clear() Use to remove all of the mappings from this map.
boolean isEmpty() Use to return true if this map contains no key-value mappings.
Object clone() Use to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Use to return a collection view of the mappings contained in this map.
Set keySet() Use to return a set view of the keys contained in this map.
V put(Object key, Object value) Use to insert an entry in the map.
void putAll(Map map) Use to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value in the map only when  specified key is not already specified.
V remove(Object key) Use to delete an entry for the specified key.
boolean remove(Object key, Object value) removes the  values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) Use 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) Use to compute its value using the given mapping function, if the specified key is not mapped with a value or null, and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) Use 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) It returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) It returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) Added in Java 8 to  performs the given action for each entry in the map  or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with respect to key.
V getOrDefault(Object key, V defaultValue) Added in Java 8. It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() It 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 then associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to specified key.
boolean replace(K key, V oldValue, V newValue) Replaces the old value with the new value with respect to specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() It returns the count of number of entries in the map.

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

class HashMapExample1 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		System.out.println("Initial hash map elements: " + hm );
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		System.out.println("\nAfter invoking put() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}

		hm.putIfAbsent(23, "Gaurav");
		System.out.println("\nAfter invoking putIfAbsent() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		HashMap map = new HashMap();
		map.put(24, "Ravi");
		map.putAll(hm);
		System.out.println("\nAfter invoking putAll() method ");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements: {}

After invoking put() method
20 Anuj
21 Virendra
22 Raghav

After invoking putIfAbsent() method
20 Anuj
21 Virendra
22 Raghav
23 Gaurav

After invoking putAll() method 
20 Anuj
21 Virendra
22 Raghav
23 Gaurav
24 Ravi

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

import java.util.*;
import java.util.HashMap;

public class HashMapExample2 {
	public static void main(String args[]) {
		HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		map.put(23, "Gaurav");
		System.out.println("Initial hash map elements: " + map);
		// key-based removal
		map.remove(20);
		System.out.println("\nUpdated hash map  elements: " + map);
		// value-based removal
		map.remove(21);
		System.out.println("\nUpdated hash map  elements: " + map);
		// key-value pair based removal
		map.remove(22, "Raghav");
		System.out.println("\nUpdated hash map  elements: " + map);
	}
}

Output :


Initial hash map elements: {20=Anuj, 21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {22=Raghav, 23=Gaurav}

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

Here you will see different ways to replace() elements in HashMap

import java.util.*;

class HashMapExample3 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");
		System.out.println("Initial hash map elements:");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(22, "Gaurav");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(21, "Virendra", "Ravi");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replaceAll((k, v) -> "Anuj");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

import java.util.*;
public class Magzine {
	int id;
	String name,author,publisher;
	int quantity;
	public Magzine(int id, String name, String author, String publisher, int quantity) {
	    this.id = id;
	    this.name = name;
	    this.author = author;
	    this.publisher = publisher;
	    this.quantity = quantity;
	}    

}
public class MapExample {
import java.util.HashMap;
import java.util.Map;

public class HashMapWithObjectsExample {

	public static void main(String[] args) {
	    //Creating map of Magzines
	    Map<Integer,Magzine> map=new HashMap<Integer,Magzine>();
	    //Creating Books
	    Magzine m1=new Magzine(21,"The Sun","Sy Sunfranchy","The Sun Company",8);
	    Magzine m2=new Magzine(22,"Glimmer Trains","Unknown","Glimmer Train Press",4);
	    Magzine m3=new Magzine(23,"Crazy horse","Brett Lot","College of Charleston",6);
	    //Adding Magzines to map
	    map.put(1,m1);
	    map.put(2,m2);
	    map.put(3,m3);  

	    //Traversing map
	    for(Map.Entry<Integer,Magzine> entry:map.entrySet()){
	        int key=entry.getKey();
	        Magzine m=entry.getValue();
	        System.out.println("\nMagzine "+key+" Details:");
	        System.out.println(m.id+" "+m.name+" "+m.author+" "+m.publisher+" "+m.quantity);
	    }
	}
}

Output :



Magzine 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Magzine 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Magzine 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

References

Java: Difference between HashMap and Hashtable


HashMap and Hashtable both implements Map interface and used to store data in key and value pairs. Both use hashing techniques to get unique keys.

Apart from some similarities, there are many differences between HashMap and Hashtable classes as follows:

java.util.HashMap java.util.HashTable
HashMap class introduced in JDK 1.2. Hashtable is a legacy class.
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
HashMap is traversed by Iterator. Hashtable is traversed by the Enumerator and Iterator.
Hashmap, Iterator is fail-fast. Hashtable, Enumerator is not fail-fast.
HashMap is not synchronized and not-thread safe. Hashtable is synchronized and thread safe.
HashMap can be synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
HashMap class allows only one null key and multiple null values. Hashtable doesn’t allow any null key or value.
HashMap is fast. Hashtable is slow.

For more detail:

 

Java: Unmodifiable Collection Methods and Example


In Collection Framework, to make collection type object as unmodifiable java.Util.Collections class provides static methods to make these object as unmodifiable.

Collections Class Unmodifiable Methods

static Collection
unmodifiableCollection(Collection<? extends T> c)
Returns an unmodifiable view of the specified collection.
static List
unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list.
static <K,V> Map<K,V>
unmodifiableMap(Map<? extends K,? extends V> m)
Returns an unmodifiable view of the specified map.
static <K,V> NavigableMap<K,V>
unmodifiableNavigableMap(NavigableMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static NavigableSet
unmodifiableNavigableSet(NavigableSet s)
Returns an unmodifiable view of the given navigable set.
static Set
unmodifiableSet(Set<? extends T> s)
Returns an unmodifiable view of the given set.
static <K,V> SortedMap<K,V>
unmodifiableSortedMap(SortedMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static SortedSet
unmodifiableSortedSet(SortedSet s)
Returns an unmodifiable view of the given  set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Unmodified. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

public class CollectionUnmodifiedExample {

	public static void main(String[] args) {
		Collection c = new ArrayList();
	    Collections.unmodifiableCollection(c);
	    Collections.unmodifiableList(new ArrayList());
	    Collections.unmodifiableMap(new HashMap());
	    Collections.unmodifiableSet(new HashSet());
	}

}

References

Java: Synchronized Collection Methods and Examples


In Collection Framework, only some of the classes are thread-safe or synchronized. If you need to work on a multi-threaded environment then you have to convert these non-synchronized type classes to Synchronized type collection.

Synchronized Collection

These are the classes only are synchronized:

  • Vector
  • HashTable

As a solution java.util.Collections class provides some static methods to make them Synchronized.

Collections Class Synchronized Methods

All these methods are static:

Collection synchronizedCollection(Collection c) Returns a synchronized collection.
List synchronizedList(List list) Returns a synchronized list.
Map<K,V>
synchronizedMap(Map<K,V> m)
Returns a synchronized map .
NavigableMap<K,V>
synchronizedNavigableMap(NavigableMap<K,V> m)
Returns a synchronized navigable map.
NavigableSet synchronizedNavigableSet(NavigableSet s) Returns a synchronized navigable set .
static Set synchronizedSet(Set s) Returns a synchronized set .
SortedMap<K,V>
synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized sorted map .
SortedSet
synchronizedSortedSet(SortedSet s)
Returns a synchronized sorted set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Synchronized. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionSunchronizationExample {

	public static void main(String[] args) {
		Collection c = Collections.synchronizedCollection(new ArrayList());
	    List list = Collections.synchronizedList(new ArrayList());
	    Set s = Collections.synchronizedSet(new HashSet());
	    Map m = Collections.synchronizedMap(new HashMap());

	}

}

References

Java: Properties Class Methods and Examples


java.util.Properties class is a subclass of HashTable. Properties class store values in key and value pairs both as String.

We can define our properties by properties (extension as .properties) or by Properties class. The main benefit of define properties in the properties file. If something needs to change then don’t need to recompile the Java Class.

Method of Properties Class

public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key, String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating the XML document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating an XML document with the specified encoding.

Example: Create Properties File

import java.io.FileWriter;
import java.util.Properties;

public class CreateProprtiesFile {

	public static void main(String[] args) throws Exception {
		Properties p = new Properties();
		//append properties in class as key and value
		p.setProperty("name", "Saurabh Gupta");
		p.setProperty("email", "FacingIssuesOnIT@gmail.com");

		//Write in properties file
		p.store(new FileWriter("myinfo.properties"),
				"FacingIssuesOnIT Properties Example");
	}
}

Output

Properties file creation

Example: Read Properties File

In this example, you will learn to read properties from the file.

import java.io.FileReader;
import java.util.Properties;

public class ReadPropertiesFile {

	public static void main(String[] args) throws Exception{
		//Read properties file
		 FileReader reader=new FileReader("myinfo.properties");   

		    Properties p=new Properties();
		    //Load file as properties
		    p.load(reader);   

		    //retrieve value of property one by one
		    System.out.println(p.getProperty("name"));
		    System.out.println(p.getProperty("email"));
	}

}

Output


Saurabh Gupta
FacingIssuesOnIT@gmail.com

Example : Print System Level Properties

import java.util.Map;
import java.util.Properties;

public class PrintSystemProperties {

	public static void main(String[] args) throws Exception{   

		//Get all properties from System class
		Properties properties=System.getProperties(); 

		//Print all System level properties
		System.out.println("Your Machine Properties :\n");
		for(Map.Entry entry:properties.entrySet())
		{
			System.out.println(entry.getKey()+" = "+entry.getValue());
		}

	}

}

Output


Your Machine Properties :

java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.8.0_73\jre\bin
java.vm.version = 25.73-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
user.country = US
user.script = 
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = 
java.vm.specification.name = Java Virtual Machine Specification
user.dir = F:\Workspace-Learning\Session8Examples
java.runtime.version = 1.8.0_73-b02
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\endorsed
os.arch = amd64
java.io.tmpdir = C:\Users\SAURAB~1\AppData\Local\Temp\
line.separator = 

java.vm.specification.vendor = Oracle Corporation
user.variant = 
os.name = Windows 10
sun.jnu.encoding = Cp1252
java.library.path = C:\Program Files\Java\jdk1.8.0_73\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_73/bin/server;C:/Program Files/Java/jre1.8.0_73/bin;C:/Program Files/Java/jre1.8.0_73/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;%JAVA_HOME%\bin;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\Saurabh Gupta\Desktop;;.
java.specification.name = Java Platform API Specification
java.class.version = 52.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 10.0
user.home = C:\Users\Saurabh Gupta
user.timezone = 
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.8
java.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\zipfs.jar;F:\Workspace-Learning\Session8Examples\bin
user.name = Saurabh Gupta
java.vm.specification.version = 1.8
sun.java.command = collections.properties.PrintSystemProperties
java.home = C:\Program Files\Java\jdk1.8.0_73\jre
sun.arch.data.model = 64
user.language = en
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.8.0_73
java.ext.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\classes
java.vendor = Oracle Corporation
file.separator = \
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = amd64

Array Data Structure and Complexity (Big-O)


“Array is collection (or group of) of homogeneous (same data type) items  referred to single variable, which store in contiguous space in memory.”

Note : Java works differently then they do in C/C++, In Java array elements are not stored in continuous locations.

For example: You have 10 integer numbers and want minimum, maximum and  average of these numbers. One way is take 10 variables and perform comparison and operations of these numbers. If numbers are in hundreds very difficult to deal with that because need to handle 100 variables. That’s what array come on picture to deal with same type data.

Points to remember:

  • Array always keep elements of same type such as primitive type or objects.
  • In Java array is dynamically allocated.
  • Array size always specified in int value not in short or long.
  • If number of elements in array are n ,then indexing of array start from 0…n-1.
  • Array is object in Java , if need to find  length, check for member length. To check length of array in C/C++ use sizeof.
  • Array can be use as static field, a local variable or a method parameter.
  • In java direct super class of Array is Object and implements java.lang.Cloneable and java.io.Serializable interface.
  • Time Complexity Access : Θ(1)
  • Time Complexity Search : Θ(n)
  • Time Complexity Insertion : Θ(n)
  • Time Complexity Deletion : Θ(n)
  • Space Complexity: O(n)

In data structure array are two types:

  • One dimensional arrays
  • Multi dimensional arrays

One Dimensional Array

One dimensional array also called as linear array.

Single Dimentional Array

Declaration of Array

Declaration show the reference of values as array and each value in array specified as type.

type var-name [];
or
type [] var-name;

Example to declare array of different types.

// both are valid way of declarations
int numbers[];
or int[] numbers; 

byte byteArr[];
short shortsArr[];
boolean booleanArr[];
long longArr[];
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>float floatArr[];
double doubleArr[];
char charArr[];
//array of reference objects of Class Type MyTestClass
MyTestClass myClassArray[]; 

//Array of unknown type object, as oBject is super class of class class
Object[]  objectArr,
//Array of unknown type of collection as Collection is super interface in Collection framework
Collection[] callectionArr;

Instantiation of Array

On array declaration only the reference of array created, to allocate memory to array need specified the size of array as below. where the size is always a integer value greater than zero.


var-name = new type[size];

For Example:

int numbers[]; //declaration
numbers=new int [10];//create an instance of array of 10 numbers.

Object[] objectArr; //declaration

objectArr=new Object[10]; //create an instance of array of 10 Objects.

Note:

  • For primitive type array instantiation, array elements values by default initialize with specified primitive default value. For example : primitive type int default value is 0, all the  elements array by default initialize with 0.
  • For reference type array instantiation, array element values by default initialize with specified primitive default value. For example : reference type Object default value is null, all the  elements array by default initialize with null.

Array Instantiation with Literals

If you already know the elements of an array , use literals in array to instantiation and assignment of values at same time.

//Array with int literals
int [] numbers={10,, 50, 70 , 90, 80};
//Array with String literals
String [] names= {"Saurabh", "Gaurav", "Raghav"};

Accessing of array

To access/assign the elements of an array, use index position within range 0 to n-1 for the size of array length n. If trying to access array beyond this range (0…n-1) for primitive and reference type, get an exception as ArrayIndexOutOfBoundException in case of String will throw StringIndexOutOfBoundsException


//accessing/assign value on array
arrName[index];

Example

//access value from array on index position 2, will result 70
int number=numbers[2];

//Assign value on index position , new change value 80
numbers[2]=80;

Java Program for Single Dimensional Array

Here is example of single line array , considering all above cases;


public class OneDimentionalArray {

	public static void main(String[] args) {

		//declaration by both ways
		int numbers[];

		//Instantion for array of int type size 10
		//By default initialize with 0 for primitive type int
		numbers=new int[10];

		//instantition with literals
		String []names= {"Saurabh","Gaurav","Raghav"};

		System.out.println("Print Numbers :");
		//access array with for loop
        for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

		// Assign values to Arrays by for loop
		for(int i=0; i<=numbers.length-1;i++)
		{
			numbers[i]=i*10;
		}

		//manually assign values,Raghav will replace with Ramesh
		names[2]="Ramesh";

		System.out.println("\n\nUpdate Values from arrays");

		//access array with for loop
                for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

	}

}

Output


Print Numbers :
0
0
0
0
0
0
0
0
0
0

Print Name :
Saurabh
Gaurav
Raghav


Update Values from arrays
0
10
20
30
40
50
60
70
80
90

Print Name :
Saurabh
Gaurav
Ramesh

Multi Dimensional Array

Multi-dimensional arrays also called Jagged Arrays, are arrays of arrays with each element of the array holding the reference of another array. A multi-dimensional array is created by appending square brackets ([]) per dimension.
For Example


int[][] intArr=new int [2][3]; //2D array
int numbers[][][]=new int [2][3][4]; //3D array

//2D representation with literals
//Create an array of size [2][3] and assign given values
int [][]numbers ={{2,5,7},{4,6,9}}

Two Dimentional Array

Java Program for Two Dimensional Array


public class TwoDimentionalArray1 {

	public static void main(String[] args) {

		//declaration
		int numbers[][] = {{2,5,7},{4,6,9}};

		//access in array of two dimensional array
        for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}

		System.out.println("\n\nUpdate Values from arrays");

		numbers[0][1]=20;
		numbers[1][2]=30;
		numbers[0][0]=40;

		for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}
	}

}

Output


numbers[0][0]=2
numbers[0][1]=5
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=9


Update Values from arrays
numbers[0][0]=40
numbers[0][1]=20
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=30

 

Java : How to remove duplicate objects from List


In this below example list having duplicate object of AccountTransaction which need to remove from list. Here I am using HashSet because it always keep unique records. Now question comes how to decide uniqueness of object. As you know contract between hashcode() and equals() method deciding uniqueness and equality of object.

Here used Comparable interface to sort values based on transaction date.

hashcode() and equals() contract :

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract.”

Example


import java.math.BigDecimal;
import java.util.Date;

public class AccountTransaction implements Comparable{
	private Date date;
	String transactionType;
	private String reference;
	private BigDecimal amount;

	public AccountTransaction(Date date, String transactionType, String reference, BigDecimal amount) {
		super();
		this.date = date;
		this.transactionType = transactionType;
		this.reference = reference;
		this.amount = amount;
	}
//Overriding toString() method to print object
	@Override
	public String toString() {
		return "AccountTransactions [date=" + date + ", transactionType=" + transactionType + ", reference=" + reference
				+ ", amount=" + amount + "]";
	}
//Overriding hashcode() and equals() method to check equality and uniqueness
//of objects
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((amount == null) ? 0 : amount.hashCode());
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result + ((reference == null) ? 0 : reference.hashCode());
		result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AccountTransaction other = (AccountTransaction) obj;
		if (amount == null) {
			if (other.amount != null)
				return false;
		} else if (!amount.equals(other.amount))
			return false;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (reference == null) {
			if (other.reference != null)
				return false;
		} else if (!reference.equals(other.reference))
			return false;
		if (transactionType == null) {
			if (other.transactionType != null)
				return false;
		} else if (!transactionType.equals(other.transactionType))
			return false;
		return true;
	}
	//Sort object by date
	@Override
	public int compareTo(AccountTransaction o) {

		return this.getDate().compareTo(o.getDate());
	}

	//use getter and setter of properties
}

Here is the class having sample data which is having duplicate objects in list. calling removeDuplicate() method which is converting list to hashSet() to remove duplicate and then again converting to list then sorting by date.


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateObjects {

	public static void main(String[] args) {
		List transactionList = new ArrayList();
		try {
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:50 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:48 AM"), "Account Debits", "Burger king",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:55 AM"), "Account Debits", "Papa Johns",new BigDecimal("2.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Debits", "Pizza hut",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));
			//Duplicate record
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
			transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));

		   System.out.println("Transactions before removing duplicate=============");
		   for(AccountTransaction transaction:transactionList)
		   System.out.println(transaction);
		   System.out.println("Transactions after removing duplicate=============");
		   transactionList=removeDuplicate(transactionList);
		   for(AccountTransaction transaction:transactionList)
			   System.out.println(transaction);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private static List removeDuplicate(List transactionList)
	{
		//Convert List to Set
		Set transactionSet=new HashSet(transactionList);
		//Convert Set to Array List
		transactionList=new ArrayList(transactionSet);

		//Sort object by transaction date and time
		Collections.sort(transactionList);

		return transactionList;
	}

	private static Date getDate(String dateStr) throws ParseException {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm a").parse(dateStr);
	}
}

Output


Transactions before removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
Transactions after removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]

See Also:

[Solved] Exception UnsupportedOperationException Example


java.lang.UnsupportedOperationException is RuntimeException and Unchecked Exception which expected to thrown by JVM(Java Virtual Machine) when try to perform an “optional operation” which is not allowed an object .

The Java framework contains plenty of these, especially in the Collections framework. For example “add” is an optional operation, because immutable collections should not allow it. Throwing UnsupportedOperationException is exactly what you should do if you don’t want to write one of these methods.

Constructors :

  • UnsupportedOprationException() : Constructs an UnsupportedOperationException with no detail message.
  • UnsupportedOprationException(String message) : Constructs an UnsupportedOperationException with specified detail message.
  • UnsupportedOprationException(String message, Throwable cause) : Constructs an UnsupportedOperationException with specified detail message and cause.
  • UnsupportedOprationException(Throwable cause) : Constructs a new exception with the  specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Example :

In below example problem is List returned from Arrays.AsList() is not like java.util.ArrayList. Arrays.asList() returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException Exception.

package exceptionhandeling;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		/**
		 * By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList.
		 * When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

		 * Not every List implementation support add method because Arrays.asList() returned
		 * immutable list of fixed size
		 */
		for(String emp:empList)
		{
			empList.add("Sachin");
			System.out.println(emp);
		}

	}

}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at example.UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:21)

Java : Comparable Vs Comparator


Comparable and Comparator both are interface used for compare and sorting collections of objects. Where  Comparable used for natural ordering of objects while Comparator used for sorting on user specific value on different type objects. In both the cases if objects are not equate or compatible will through ClassCastException.

In below links, I have explained about in depth detail about Comparable and Comparator implementation and cases where to use. Here mainly focus on some points for technical, implementation and functional points.

Comprable :Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

How to sort object by Comparator interface in ascending and descending order : JAVA

Difference between Comparable and Comparator

Comparable Comparator
Comparable is in java lang package as java.lang.Comparable. Comparator is in java util package as java.util.Comparator.
Method used int compareTo(Object t); Method used int compare(Object t1 , Object t2);

Comparable is used to compare itself by using with another object.

Here modify the class whose instance you want to sort. So that only one sort sequence can be created per class.

Comparator is used to compare two datatypes are objects.

Here build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class.

 A comparable used for default and natural ordering of objects.  A comparator represents the ordering itself for specific use.

Some java classes having build in Comparable interface like String, Date, Wrapper Classes etc.

Some classes actually provide Comparators for common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER.
 For sorting use methods like Collections.Sort(List) or Array.sort().  For Sorting use method Collections.sort(List, Comparator).

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

How to sort object by Comparator interface in ascending and descending order : JAVA


As in previous posts shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface and also sort user-defined classes by implements  Comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

Java : Comparable Vs Comparator

What is Comparator Interface?

java.util.Comparator  interface imposes user define sorting on different class fields  based on comparing values from different objects.  It provide compare() method which compares two objects  and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparator Interface?

Below is syntax of compare method:

public interface Comparator {
    public int compare(T o1, T o2);

}

compare() method compare two objects  fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparator interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparator  interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparable.

Note :  Below example is base on List of Employee objects it cannot be used to order a sorted collection, such as TreeSet because it generates an ordering that is not compatible with equals. It means that Comparator equates objects that the equals method does not.

In particular, any two employees who were joined on the same date will compare as equal. When you’re sorting a List this doesn’t matter; but when you’re using the Comparator to order a sorted collection, it’s fatal. If you use this Comparator to insert multiple employees joined on the same date into a TreeSet only the first one will be added to the set; the second will be seen as a duplicate element and will be ignored.

Example :

Below is simple Employee class which is having fields and getter/setter methods and also constructor to create object.

package sorting
public class Employee {
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{
}
//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}
}

Here we have created EmpComparator class and implements compare() method  of java.util.Comparator interface which will compare object fields values based on selected fields on time of sorting. ex: sortingField value.

For example : sortingField value as firstName then compare() method of  java.util.Comparator  interface will compare firstName value of passing two object on compare() method and return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;
import java.util.Comparator;

public class EmpComparator implements Comparator {
	public static final String ID = "id";
	public static final String FIRST_NAME = "firstName";
	public static final String LAST_NAME = "lastName";
	public static final String DESIGNATION = "designation";
	public static final String SALARY = "salary";
	public static final String AGE = "age";
	private String sortingField;

	@Override
	public int compare(Employee emp1, Employee emp2) {
		int diff = 0;
		switch (sortingField) {
		case ID:
			diff=emp1.getId()-emp2.getId();
			break;
		case FIRST_NAME:
			diff=emp1.getFirtsName().compareTo(emp2.getFirtsName());
			break;
		case LAST_NAME:
			diff=emp1.getLastName().compareTo(emp2.getLastName());
			break;
		case DESIGNATION:
			diff=emp1.getDesignation().compareTo(emp2.getDesignation());
			break;
		case SALARY:
			diff=(int)(emp1.getSalary()-emp2.getSalary());
			break;
		case AGE:
			diff=emp1.getAge()-emp2.getAge();
			break;

		}
		return diff;
	}

	public String getSortingField() {
		return sortingField;
	}

	public void setSortingField(String sortingField) {
		this.sortingField = sortingField;
	}
}

Here in below example creating List of Employee objects for sorting in ascending and descending order.

For sorting by firstName assigning value of sortingField as “firstName” in empComparator object. First we are using Collections.sort(List, Comparator) sorting method to sort list in ascending order by firstName because current value of sortingField is firstName. For descending order we will just reverse order of objects by Collections.resverse() method. Similarly using for lastName and also try with other fields of Employee class.

package sorting;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortComparator {

	public static void main(String[] args) {
		Employee[] empArr = {
				new Employee(1, "Saurabh", "Gupta", "Sr Project Lead", 60000, 35),
				new Employee(2, "Gaurav", "Gupta", "Developer", 50000, 32),
				new Employee(3, "Shailesh", "Nagar", "Manager", 100000, 36),
				new Employee(4, "Ankur", "Mehrotra", "Lead", 55000, 30),
				new Employee(5, "Ranjith", "Ranjan", "Tester", 35000, 45),
				new Employee(6, "Ramesh", "Bhardwaj", "Support", 25000, 35)
				};
		// Convert Array to LIst
		List empList = Arrays.asList(empArr);
		// Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		// Sort List in Ascending order by first Name
		EmpComparator empComparator = new EmpComparator();
		empComparator.setSortingField("firstName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by FirtName
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

		// Sort List in Ascending order by lastName

		empComparator.setSortingField("lastName");
		Collections.sort(empList, empComparator);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		// Sort List in Descending order by last Name
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList) {
		for (Employee emp : empList) {
			System.out.println(emp);<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
		}
	}
}

Output :

********Print Employee List Before Sort********
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]

********Print Employee List in Ascending Order********
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]

********Print Employee List in Descending Order********
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]

********Print Employee List in Ascending Order********
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]

********Print Employee List in Descending Order********
Employee [id=5, firtsName=Ranjith, lastName=Ranjan, designation=Tester, salary=35000.0, age=45]
Employee [id=3, firtsName=Shailesh, lastName=Nagar, designation=Manager, salary=100000.0, age=36]
Employee [id=4, firtsName=Ankur, lastName=Mehrotra, designation=Lead, salary=55000.0, age=30]
Employee [id=2, firtsName=Gaurav, lastName=Gupta, designation=Developer, salary=50000.0, age=32]
Employee [id=1, firtsName=Saurabh, lastName=Gupta, designation=Sr Project Lead, salary=60000.0, age=35]
Employee [id=6, firtsName=Ramesh, lastName=Bhardwaj, designation=Support, salary=25000.0, age=35]
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

How to Sort By Comparable Interface in Ascending and Descending Order : Java


As in previous post shown like wrapper of primitive type , String and Date classes having  implements in-built comparable interface which provide natural or chronological or alphabetical sorting of elements.

Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to sort object by Comparator interface in ascending and descending order : JAVA

Java : Comparable Vs Comparator

What is Comparable Interface?

java.lang.Comparable  interface imposes a total natural ordering on the objects of each class that implements it.  it provide compareTo() method which compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.

How to use Comparable Interface?

Below is syntax of compareTo method:

public interface Comparable {
    public int compareTo(T o);

}

compareTo() method compare current object (this)  fields values with passing object fields values and return negative integer, 0 or a positive integer and Collections.sort() method will sort based on this return value.

Lists (and arrays) of objects that implement this comparable interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this comparable interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Example :

Below Employee class implements compareTo() method of  java.lang.Comparable  interface which is comparing firstName value with specified object firstName value. This  method return a integer value like (negative integer, 0 or positive integer) depend on compare result.

package sorting;

public class Employee implements Comparable{
private int id;
private String firtsName;
private String lastName;
private String designation;
private double salary;
private int age;

//Default Constructor
public Employee()
{

}

//Parametrize Constructor
public Employee(int id, String firtsName, String lastName, String designation, double salary, int age) {
	super();
	this.id = id;
	this.firtsName = firtsName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.age = age;
}

@Override
public int compareTo(Employee employee) {
	//sort by firstName
	return this.firtsName.compareTo(employee.firtsName);
}

public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getFirtsName() {
	return firtsName;
}
public void setFirtsName(String firtsName) {
	this.firtsName = firtsName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public String getDesignation() {
	return designation;
}
public void setDesignation(String designation) {
	this.designation = designation;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}

@Override<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
public String toString() {
	return "Employee [id=" + id + ", firtsName=" + firtsName + ", lastName=" + lastName + ", designation=" + designation
			+ ", salary=" + salary + ", age=" + age + "]";
}

}

In below class sorting  Employee list objects by names in ascending order by Collections.sort(list). As shown above Employee Class implements  Comparable interface and it’s  compareTo() method  will sort elements in Ascending order by firstName on objects.

For Descending order used Collections.reverse(List) reverse method which will reverse list of sorted list.

 

package sorting;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortComparable {

	public static void main(String[] args) {
		Employee [] empArr={
				new Employee(1,"Saurabh","Gupta","Sr Project Lead",60000,35),
				new Employee(2,"Gaurav","Gupta","Developer",50000,32),
				new Employee(3,"Shailesh","Nagar","Manager",100000,36),
				new Employee(4,"Ankur","Mehrotra","Lead",55000,30),
				new Employee(5,"Ranjith","Ranjan","Tester",35000,45),
				new Employee(6,"Ramesh","Bhardwaj","Support",25000,35)
				};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		//Print Assigned Values Before Sort;
		System.out.println("********Print Employee List Before Sort********");
		printArrayList(empList);

		//Sort List in Ascending order by collections api
		Collections.sort(empList);
		System.out.println("\n********Print Employee List in Ascending Order********");
		printArrayList(empList);

		//Sort List in Descending order by collections api
		Collections.reverse(empList);
		System.out.println("\n********Print Employee List in Descending Order********");
		printArrayList(empList);

	}

	private static void printArrayList(List empList)
	{
		for(Employee emp:empList)
		{
			System.out.println(emp);
		}
	}
}

 

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

How to convert ArrayList to Array and Array to ArrayList?


Arrays class provide method Arrays.asList()  which convert array type elements to a unmodified fixed size ArrayList.

Same way List provide method as List.toArray(List) which convert ArrayList elements to Array.

Note : List returned from Arrays.AsList() is not like java.util.ArrayList. It
returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException

Example : 

In below example used method Arrays.asList()  to convert  String array to ArrayList of String elements. On other  side use List.toArray() method to convert ArrayList elements to Arrays of type String elements.

package exceptionhandeling;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayToArrayListConversion {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		System.out.println("*****Print ArrayList*****");
		printArrayList(empList);
		//Convert ArrayList to Array
		 empArr=(String[])empList.toArray();
		 System.out.println("*****Print Array*****");
		 printArray(empArr);
	}
	private static void printArrayList(List empList)
	{
		for(String emp:empList)
		{
			System.out.println(emp);
		}
	}
	private static void printArray(String[] empArr)
	{
		for(String emp:empArr)
		{
			System.out.println(emp);
		}
	}
}

Output:

*****Print ArrayList*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh
*****Print Array*****
Saurabh
Gaurav
Shailesh
Ankur
Ranjith
Ramesh