Collections Class in Java

Last updated on Dec 11 2022
Prabhas Ramanathan

Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class.
The important points about Java Collections class are:
• Java Collection class supports the polymorphic algorithms that operate on collections.
• Java Collection class throws a NullPointerException if the collections or class objects provided to them are null.
Collections class declaration
Let’s see the declaration for java.util.Collections class.
1. public class Collections extends Object

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

Table of Contents

Java Collections Example

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<String> list = new ArrayList<String>();
5. list.add(“C”);
6. list.add(“Core Java”);
7. list.add(“Advance Java”);
8. System.out.println(“Initial collection value:”+list);
9. Collections.addAll(list, “Servlet”,”JSP”);
10. System.out.println(“After adding elements collection value:”+list);
11. String[] strArr = {“C#”, “.Net”};
12. Collections.addAll(list, strArr);
13. System.out.println(“After adding array collection value:”+list);
14. }
15. }
Output:
Initial collection value:[C, Core Java, Advance Java]
After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP]
After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#, .Net]

Java Collections Example: max()

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<Integer> list = new ArrayList<Integer>();
5. list.add(46);
6. list.add(67);
7. list.add(24);
8. list.add(16);
9. list.add(8);
10. list.add(12);
11. System.out.println(“Value of maximum element from the collection: “+Collections.max(list));
12. }
13. }
Output:
Value of maximum element from the collection: 67

Java Collections Example: min()

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<Integer> list = new ArrayList<Integer>();
5. list.add(46);
6. list.add(67);
7. list.add(24);
8. list.add(16);
9. list.add(8);
10. list.add(12);
11. System.out.println(“Value of minimum element from the collection: “+Collections.min(list));
12. }
13. }
Output:
Value of minimum element from the collection: 8

Sorting in Collection

We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type.
Note: String class and Wrapper classes implement the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Example to sort string objects
1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add(“Viru”);
7. al.add(“Saurav”);
8. al.add(“Mukesh”);
9. al.add(“Tahir”);
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now
Mukesh
Saurav
Tahir
Viru

Example to sort string objects in reverse order
1. import java.util.*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add(“Viru”);
7. al.add(“Saurav”);
8. al.add(“Mukesh”);
9. al.add(“Tahir”);
10.
11. Collections.sort(al,Collections.reverseOrder());
12. Iterator i=al.iterator();
13. while(i.hasNext())
14. {
15. System.out.println(i.next());
16. }
17. }
18. }
Viru
Tahir
Saurav
Mukesh

Example to sort Wrapper class objects
1. import java.util.*;
2. class TestSort3{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
101
201
230

Example to sort user-defined class objects
1. import java.util.*;
2.
3. class Student implements Comparable<Student> {
4. public String name;
5. public Student(String name) {
6. this.name = name;
7. }
8. public int compareTo(Student person) {
9. return name.compareTo(person.name);
10.
11. }
12. }
13. public class TestSort4 {
14. public static void main(String[] args) {
15. ArrayList<Student> al=new ArrayList<Student>();
16. al.add(new Student(“Viru”));
17. al.add(new Student(“Saurav”));
18. al.add(new Student(“Mukesh”));
19. al.add(new Student(“Tahir”));
20.
21. Collections.sort(al);
22. for (Student s : al) {
23. System.out.println(s.name);
24. }
25. }
26. }
Mukesh
Saurav
Tahir
Viru

So, this brings us to the end of blog. This Tecklearn ‘Collections Class in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

 

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Collections Class in Java"

Leave a Message

Your email address will not be published. Required fields are marked *