Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate
the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
No. Method Description
1 public boolean add(Object element) is used to insert an element in this collection.
2 public boolean addAll(Collection c) is used to insert the specified collection elemen
collection.
3 public boolean remove(Object is used to delete an element from this collection.
element)
4 public boolean removeAll(Collection is used to delete all the elements of specified
c) invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking co
specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
8 public boolean contains(Object is used to search an element.
element)
9 public boolean containsAll(Collection is used to search the specified collection in this collec
c)
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object matches two collection.
element)
14 public int hashCode() returns the hashcode number for collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. Method Description
1 public boolean hasNext() It returns true if iterator has more elements.
2 public Object next() It returns the element and moves the cursor pointer to the ne
3 public void remove() It removes the last elements returned by the iterator. It is rar
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.
1. ArrayList al=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
The important points about Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
Java ArrayList Example
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Test it Now
Ravi
Vijay
Ravi
Ajay
Two ways to iterate the elements of collection in
java
There are two ways to traverse collection elements:
1. By Iterator interface.
2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example
to traverse ArrayList elements using for-each loop.
Iterating Collection through for-each loop
1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
Test it Now
Ravi
Vijay
Ravi
Ajay
User-defined class objects in Java ArrayList
Let's see an example where we are storing Student class object in array list.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method
1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Sonoo");
10. al2.add("Hanumat");
11. al.addAll(al2);//adding second list in first list
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat
Example of removeAll() method
1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.removeAll(al2);
12. System.out.println("iterating the elements after removing the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17.
18. }
19. }
Test it Now
iterating the elements after removing the elements of al2...
Vijay
Ajay
Example of retainAll() method
1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }
Test it Now
iterating the elements after retaining the elements of al2...
Ravi
Java ArrayList Example: Book
Let's see an ArrayList example where we are adding books to list and printing all the books.
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill"
,4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Set in Java
Set is an interface which extends Collection. It is an unordered collection of
objects in which duplicate values cannot be stored.
Basically, Set is implemented by HashSet, LinkedSet or TreeSet (sorted
representation).
Set has various methods to add, remove clear, size, etc to enhance the usage
of this interface
// Java code for adding elements in Set
import java.util.*;
public class Set_example
{
public static void main(String[] args)
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
Output:
Set output without the duplicates[Geeks, Example, For, Set]
Sorted Set after passing into TreeSet[Example, For, Geeks, Set]\
Java Map Interface
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is
known as an entry. Map contains only unique keys.
Map is useful if you have to search, update or delete elements on the basis of key.
Useful methods of Map interface
Method Description
Object put(Object key, Object value) It is used to insert an entry in this map.
void putAll(Map map) It is used to insert the specified map in this map.
Object remove(Object key) It is used to delete an entry for the specified key.
Object get(Object key) It is used to return the value for the specified key.
boolean containsKey(Object key) It is used to search the specified key from this map.
Set keySet() It is used to return the Set view containing all the keys.
Set entrySet() It is used to return the Set view containing all the keys
Map.Entry Interface
Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides
methods to get key and value.
Methods of Map.Entry interface
Method Description
Object getKey() It is used to obtain key.
Object getValue() It is used to obtain value.
Java Map Example: Generic (New Style)
1. import java.util.*;
2. class MapInterfaceExample{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. for(Map.Entry m:map.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
Output:
102 Rahul
100 Amit
101 Vijay
Java Map Example: Non-Generic (Old Style)
1. //Non-generic
2. import java.util.*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. map.put(1,"Amit");
8. map.put(5,"Rahul");
9. map.put(2,"Jai");
10. map.put(6,"Amit");
11. //Traversing Map
12. Set set=map.entrySet();//Converting to Set so that we can traverse
13. Iterator itr=set.iterator();
14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can get key and value separately
16. Map.Entry entry=(Map.Entry)itr.next();
17. System.out.println(entry.getKey()+" "+entry.getValue());
18. }
19. }
20. }
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
What is difference between HashMap and TreeMap?
HashMap TreeMap
1) HashMap can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.
Let us consider below example where we have to count occurrences
of each integer in given array of integers.
Input: arr[] = {10, 3, 5, 10, 3, 5, 10};
Output: Frequency of 10 is 3
Frequency of 3 is 2
Frequency of 5 is 2
/* Java program to print frequencies of all elements using
HashMap */
import java.util.*;
class Main
{
// This function prints frequencies of all elements
static void printFreq(int arr[])
{
// Creates an empty HashMap
HashMap<Integer, Integer> hmap =
new HashMap<Integer, Integer>();
// Traverse through the given array
for (int i = 0; i < arr.length; i++)
{
Integer c = hmap.get(arr[i]);
// If this is first occurrence of element
if (hmap.get(arr[i]) == null)
hmap.put(arr[i], 1);
// If elements already exists in hash map
else
hmap.put(arr[i], ++c);
}
// Print result
for (Map.Entry m:hmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}
// Driver method to test above method
public static void main (String[] args)
{
int arr[] = {10, 34, 5, 10, 3, 5, 10};
printFreq(arr);
}
}
Run on IDE
Output:
Frequency of 34 is 1
Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3
Key Points
HashMap does not maintain any order neither based on key nor on basis of
value, If we want the keys to be maintained in a sorted order, we need to use
TreeMap.
Complexity: get/put/containsKey() operations are O(1) in average case but we
can’t guarantee that since it all depends on how much time does it take to
compute the hash.
Application:
HashMap is basically an implementation of hashing. So wherever we
need hashing with key value pairs, we can use HashMap. For example,
in Web Applications username is stored as a key and user data is
stored as a value in the HashMap, for faster retrieval of user data
corresponding to a username.
TreeMap
TreeMap can be a bit handy when we only need to store unique elements in a sorted
order. Java.util.TreeMap uses a red-black tree in the background which makes sure
that there are no duplicates; additionally it also maintains the elements in a sorted
order.
TreeMap<K, V> hmap = new TreeMap<K, V>();
Below is TreeMap based implementation of same problem. This
solution has more time complexity O(nLogn) compared to previous one
which has O(n). The advantage of this method is, we get elements in
sorted order.
/* Java program to print frequencies of all elements using
TreeMap */
import java.util.*;
class Main
{
// This function prints frequencies of all elements
static void printFreq(int arr[])
{
// Creates an empty TreeMap
TreeMap<Integer, Integer> tmap =
new TreeMap<Integer, Integer>();
// Traverse through the given array
for (int i = 0; i < arr.length; i++)
{
Integer c = tmap.get(arr[i]);
// If this is first occurrence of element
if (tmap.get(arr[i]) == null)
tmap.put(arr[i], 1);
// If elements already exists in hash map
else
tmap.put(arr[i], ++c);
}
// Print result
for (Map.Entry m:tmap.entrySet())
System.out.println("Frequency of " + m.getKey() +
" is " + m.getValue());
}
// Driver method to test above method
public static void main (String[] args)
{
int arr[] = {10, 34, 5, 10, 3, 5, 10};
printFreq(arr);
}
}
Run on IDE
Output:
Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3
Frequency of 34 is 1
// Java program to demonstrate working of Map interface
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm =
new HashMap< String,Integer>();
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));
// Returns Set view
Set< Map.Entry< String,Integer> > st = hm.entrySet();
for (Map.Entry< String,Integer> me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}
Run on IDE
Output:
a:100
b:200
c:300
d:400
Difference between HashSet and HashMap
HashSet contains only values whereas HashMap contains entry(key and value).
Java HashMap Example: Book
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new HashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill"
,4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
Deque
package com.example;
import java.util.ArrayDeque;
import java.util.Deque;
public class IntegerStack {
private Deque<Integer> data = new ArrayDeque<Integer>();
public void push(Integer element) {
data.addFirst(element);
}
public Integer pop() {
if(data.isEmpty())
{
System.out.print("Stack is empty");
}
return data.removeFirst();
}
public Integer peek() {
return data.peekFirst();
}
public String toString() {
return data.toString();
}
public static void main(String[] args) {
IntegerStack stack = new IntegerStack();
for (int i = 0; i < 5; i++) {
stack.push(i);
}
System.out.println("After pushing 5 elements: " + stack);
int element = stack.pop();
System.out.println("Popped element = " + element);
System.out.println("After popping 1 element : " + stack);
int top = stack.peek();
System.out.println("Peeked element = " + top);
System.out.println("After peeking 1 element : " + stack);
}
}
Sorting in Collection
Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.
The Collections API provides two interfaces for ordering elements: Comparable and
Comparator.
The Comparable interface is implemented in a class and provides a single sorting option for
the class.
The Comparator interface enables you to create multiple sorting options. You plug in the
designed option whenever you want.
Both interfaces can be used with sorted collections, such as TreeSet and TreeMap.
Example of Sorting the elements of List that
contains 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
Output:Mukesh
Saurav
Tahir
Viru
Example of Sorting the elements of List that
contains Wrapper class objects
1. import java.util.*;
2. class TestSort2{
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. }
Test it Now
Output:101
201
230
Java Comparator Example (Non-generic Old
Style)
Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than
the second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age
of first object is less than the second object, we are returning negative value, it can be any
negative value and if age of both objects are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Java Comparator Example (Generic)
Student.java
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name...");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("sorting by age...");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24.
25. }
26. }
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Java Comparable Example
Let's see the example of Comparable interface that sorts the list elements on the basis of age.
File: Student.java
1. class Student implements Comparable<Student>{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Student st){
12. if(age==st.age)
13. return 0;
14. else if(age>st.age)
15. return 1;
16. else
17. return -1;
18. }
19. }
File: TestSort3.java
1. import java.util.*;
2. import java.io.*;
3. public class TestSort3{
4. public static void main(String args[]){
5. ArrayList<Student> al=new ArrayList<Student>();
6. al.add(new Student(101,"Vijay",23));
7. al.add(new Student(106,"Ajay",27));
8. al.add(new Student(105,"Jai",21));
9.
10. Collections.sort(al);
11. for(Student st:al){
12. System.out.println(st.rollno+" "+st.name+" "+st.age);
13. }
14. }
15. }
16.
Test it Now
Output:105 Jai 21
101 Vijay 23
106 Ajay 27