Blog Details

Collections & Arrays Class in Java SE

1. Collections

This class consists exclusively of static methods that operate on or return collections.

Common methods:

  • int maxVal = Collections.max(list)
  • int minVal = Collections.min(list)
  • Collections.reverse(list); // Return the reversed order of the list
  • Collections.rotate(list, distance); // Rotate the list
  • Collections.shuffle(list); // Shuffle the list
  • Collections.sort(list); // Sort the list in a natural order.
  • Collections.swap(list, i, j); // Swap the value in j and i.
package com.frank.collections;


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

import org.junit.jupiter.api.Test;

public class CollectionsTest {
	
	@Test
	public void test1() {
		ArrayList<Integer> list = new ArrayList<Integer>();
		// 3, 5, 19, 8, 22, 12, 58, 34
		list.add(3);
		list.add(5);
		list.add(19);
		list.add(8);
		list.add(22);
		list.add(12);
		list.add(58);
		list.add(34);
		System.out.println(list);
		int maxVal = Collections.max(list);
		System.out.println("Max Value: " + maxVal);
		int minVal = Collections.min(list);
		System.out.println("Min Value: " + minVal);
		Collections.sort(list);
		System.out.println("Sorted: " + list);
		Collections.reverse(list);
		System.out.println("Reversed: " + list);
		Collections.rotate(list, 2);
		System.out.println("Rotated: -> 1: " + list);
		Collections.shuffle(list);
		System.out.println("Shuffled: " + list);
		Collections.swap(list, 0, 3);
		System.out.println("Swaped(0, 3): " + list);
	}
	
}

2. Arrays

Sorting and search in the array.

Usually, if we need to manipulate an array, the first utility class you should consider is Arrays.

Methods:

  • Arrays.asList(T...a);
  • Arrays.binarySearch(T[] a, T key); // Can also do binary search in a certain range
  • Arrays.parallelSort(T[] a);
  • Arrays.sort(T[] a)
  • Arrays.toString(T[] a);
  • Arrays.stream(T[] a)
package com.frank.arrays;

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

import org.junit.jupiter.api.Test;

public class ArraysTest {
	@Test
	public void testArrays() {
		int[] arr = {43, 11, 89, 77, 52, 111, 7, 62};
		System.out.print("Before sort: ");
		for(Integer val : arr) {
			System.out.print(val + " ");
		}
		System.out.println();
		// binary search 11
		int indexOfVal = Arrays.binarySearch(arr, 11);
		System.out.println("Binary search: get index of 11: " + indexOfVal);
		// Do the parallel sort in ascending order
		System.out.print("Parallel sort: (ascending order)");
		Arrays.parallelSort(arr);
		for(Integer val : arr) {
			System.out.print(val + " ");
		}
		System.out.println();
		System.out.println("Sort(): (descending order)");
		Arrays.sort(arr, Collections.reverseOrder());
		for(Integer val : arr) {
			System.out.print(val + " ");
		}
	}
}