Master java skills

Collections class

Collections class is a utility class in java.util package, which exposes a lot of static methods to work with collection classes. One of the examples, we have already used – Collections.sort(List<T> list). Other examples are Collections.binarySearch() and Collections.reverse() etc.

There are a lot of utility methods that can be used in conjunction with collection framework classes.

Class Declaration

public class Collections extends Object

Collections.max() method example

max() method returns the maximum value from a list.

package com.javatrainingschool;

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

public class CollectionsExample {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(20);
		list.add(30);
		list.add(10);
		list.add(100);
		list.add(40);
		list.add(90);
		System.out.println("Max value in the list = " + Collections.max(list));
	}
}
Output :
Max value in the list = 100

Collections.copy() method example

copy() method is used to copy one list to another. Destination list where source list is to be copied should be at least as long as the source list.

package com.javatrainingschool;

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

public class CollectionsExample {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(20);
		list.add(30);
		list.add(10);
		list.add(100);
		list.add(40);
		list.add(90);
		
		List<Integer> list1 = new ArrayList<Integer>();
		list1.add(300);
		list1.add(400);
		
		Collections.copy(list, list1);
		System.out.println(list);
	}
}
Output :
[300, 400, 10, 100, 40, 90]

Collections.addAll() example

addAll() method adds all the values to the specified collection.

package com.javatrainingschool;

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

public class CollectionsExample {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(20);
		list.add(30);
		list.add(10);
		list.add(100);
		list.add(40);
		list.add(90);
		
		Collections.addAll(list, 300, 400, 500);
		System.out.println(list);
	}
}
Output :
[20, 30, 10, 100, 40, 90, 300, 400, 500]