Collections

java.util.Collections Example

In this article we will discuss about the Collections class and some of its important methods. The class java.util.Collections is a utility class that resides in java.util package, it consists entirely of static methods which are used to operate on collections like List, Set. Common operations like sorting a List or finding an element from a List can easily be done using the Collections class.

We will use an ArrayList in the following examples to illustrate the use of Collections class. The list in the examples stores elements of type Double. Let us assume this list contains temperature of a place.

 

1. Let’s sort, search, shuffle, and fill a list using Collections

CollectionsExample.java

package com.javacodegeeks.corejava.util;

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

public class CollectionsExample {

	public static void main(String[] args) {
		
		List<Double> temperatureList = new ArrayList<Double>();
		
		temperatureList.add(40.5);
		temperatureList.add(33.9);
		temperatureList.add(37.8);
		temperatureList.add(15.3);
		temperatureList.add(25.6);
		
		// Print elements of temperatureList
		System.out.println(temperatureList);
		
		// Sorting List in ascending order according to the natural ordering 
		Collections.sort(temperatureList);
		System.out.println("Sorted List: "+temperatureList);
		
		// Searching a temperature from list
		int searchIndex = Collections.binarySearch(temperatureList, 37.8);
		if(searchIndex >=0){
			System.out.println("Temperature found.");
		}
		else{
			System.out.println("Temperature not found.");
		}
		
		//Shuffles the list
		Collections.shuffle(temperatureList);
		System.out.println("Shuffled List: "+temperatureList);
		
		//Fill temperatureList.
		Collections.fill(temperatureList, 0.0);
		System.out.println("Filled List: "+temperatureList);
			
	}
}

Let’s explain the methods used in the above example.
Collections.sort(List<T extends Comparable<? super T>> list) is used to sort the given list in ascending order according to the natural ordering.

Collections.binarySearch(List<T extends Comparable<? super T>> list, T key) is used to search the element T in the given list. It returns an index of the searched element if found; otherwise (-) insertion point. Please note that the list must be in sorted into ascending order before calling this method otherwise result would not be as expected.

Collections.shuffle(List<?> list) is used to randomly shuffle the elements in the list. It will give different results in different call.

Collections.fill(List<? super T> list, T obj) is used to replace the elements of the given list with the specified element. As shown in this example we have replaced all temperature of the list with 0.0.

  • If we run the above code, we will have the following results:
[40.5, 33.9, 37.8, 15.3, 25.6]
Sorted List: [15.3, 25.6, 33.9, 37.8, 40.5]
Temperature found.
Shuffled List: [33.9, 25.6, 40.5, 15.3, 37.8]
Filled List: [0.0, 0.0, 0.0, 0.0, 0.0]

2. Let’s see some more methods of Collections class

MyCollectionsExample.java

package com.javacodegeeks.corejava.util;

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

public class MyCollectionsExample {
	
	public static void main(String[] args) {
		
		List<Double> temperatureList = new ArrayList<Double>();
		
		temperatureList.add(33.9);
		temperatureList.add(37.8);
		temperatureList.add(40.5);
		temperatureList.add(15.3);
		temperatureList.add(25.6);
		
		// Print elements of temperatureList
		System.out.println(temperatureList);
		
		//Get maximum temperature from temperatureList
		Double max = Collections.max(temperatureList);
		System.out.println("Maximun temperature: "+max);
		
		//Get minimum temperature from temperatureList
		Double min = Collections.min(temperatureList);
		System.out.println("Minimum temperature: "+min);
		
		//Reverse the list
		Collections.reverse(temperatureList);
		System.out.println("Reversed List: "+temperatureList);
		
		//Copy elements from one list to another
		List<Double> temperatureList = new ArrayList<Double>(temperatureList.size());
		newTemperatureList.add(13.6);
		newTemperatureList.add(10.2);
		newTemperatureList.add(42.9);
		newTemperatureList.add(34.4);
		newTemperatureList.add(27.2);
		System.out.println("New temperature list: "+newTemperatureList);
		Collections.copy(newTemperatureList, temperatureList);
		System.out.println("New temperature list after copy: "+newTemperatureList);
		
		//Replaces all occurrences of one specified value in a list with another.
		Collections.replaceAll(temperatureList, 40.5, 0.0);
		System.out.println("After replaceAll: "+temperatureList);
		
	}

}

Let’s explain the methods used in the above example.
Collections.max(Collection<? extends T> coll) returns the maximum element of the given collection, according to the natural ordering of its elements. We used it to get the maximum temperature in the given list.

Collections.min(Collection<? extends T> coll) returns the minimum element of the given collection, according to the natural ordering of its elements.We used it to get the minimum temperature in the given list.

Collections.reverse(List<?> list), reverses the order of the elements in the specified list.

Collections.copy(List<? super T> dest, List<? extends T> src) it copies all the elements from one list into another. After this method the index of each copied element in the destination list will be identical to its index in the source list. Destination list needs to be equal or bigger in the size.

  • If we run the above code, we will have the following results:
[33.9, 37.8, 40.5, 15.3, 25.6]
Maximun temperature: 40.5
Minimum temperature: 15.3
Reversed List: [25.6, 15.3, 40.5, 37.8, 33.9]
New temperature list: [13.6, 10.2, 42.9, 34.4, 27.2]
New temperature list after copy: [25.6, 15.3, 40.5, 37.8, 33.9]
After replaceAll: [25.6, 15.3, 0.0, 37.8, 33.9]

This was an example of how to use the Collections class and some of its basic methods.

3. Download the source code

You can download the source code of this example from here: CollectionsExample.zip

Rohit Joshi

Rohit Joshi works as a Software Engineer in the Consumer Product Sector. He is a Sun Certified Java Programmer. He had worked in projects related to different domains. He is also involved in system analysis and system designing. He mainly works in Core Java and J2EE technologies but also have good experience in front-end technologies like Javascript and Jquery.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Suhail Ahmed Malik
5 years ago

nice piece of explanation on collection

Back to top button