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.
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 Comparable type.
Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains string objects-
import java.util.*; class Simple12{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add("Dinesh"); al.add("Sweetu"); al.add("Adesh"); al.add("Vinesh"); Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
Example of Sorting the elements of List that contains Wrapper class objects
import java.util.*; class Simple12{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(Integer.valueOf(201)); al.add(Integer.valueOf(101)); al.add(230);//internally will be converted into objects as Integer.valueOf(230) Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…