Home > Java > javaTutorial > body text

Sort Java vectors in descending order using comparator

WBOY
Release: 2023-08-20 19:17:03
forward
724 people have browsed it

Sort Java vectors in descending order using comparator

Vectors implements the List interface and is used to create dynamic arrays. Arrays whose size is not fixed and can grow as per our requirement are called dynamic arrays. Comparator is an interface available in the ‘java.util’ package.

Sort means to rearrange the elements of a given list or array in ascending or descending order. In this article, we will create a vector and then try to sort its elements in descending order using a comparator.

Program to sort Java vectors in descending order

Comparator

As its name suggests, it is used to compare something. In Java, Comparator is an interface for sorting custom objects. We can write our own logic to sort the specified objects in its built-in method "compare()". This method accepts two objects as parameters and returns an integer value. Through this integer value, the Comparator determines which object is larger.

Syntax

Comparator< TypeOfComparator > nameOfComparator = new Comparator< TypeOfComparator >() {
   compare( type object1, type object1 ) {
      // logic for comparison
   }
};
Copy after login

In a method like 'Collection.sort()', nameOfComparator is the parameter used for the sorting operation.

Collections.sort() method

The class ‘Collections’ of the Collection Interface provides a static method named ‘Collections.sort()’ that can sort elements of specified collections like ArrayList or LinkedList. It is available in ‘java.util’ package.

Syntax

Collections.sort( nameOfcollection, ComparatorObject );
Copy after login

Collections.reverseOrder()

It returns the comparator in reverse order.

Example 1

In the following example, we will define a vector named 'vectlist' and store a few objects in it by using the 'add()' method. Then, use the Comparator object and 'Collection.sort()' method to sort the vector in descending order.

import java.util.*;
public class VectClass {
   public static void main(String args[]) {
      // Creation of vector 
      Vector<Integer> vectList = new Vector<>();
      // Adding elements in the vector
      vectList.add(97);
      vectList.add(93);
      vectList.add(95);
      vectList.add(99);
      vectList.add(82);
      vectList.add(88);
      System.out.println("Elements of the unsorted list: ");
      // loop to iterate through elements
      for(int i = 0; i < vectList.size(); i++ ) {
         // to print the elements of the vector
         System.out.print(vectList.get(i) + " "); 
      }
      System.out.println();
      // Using comparator interface for sorting
      Comparator comp = Collections.reverseOrder();
      Collections.sort(vectList, comp);
      System.out.println("Elements of the newly sorted list: ");
      // loop to iterate through elements
      for(int i = 0; i < vectList.size(); i++ ) {
         // to print the elements of the new vector
		   System.out.print(vectList.get(i) + " "); 
      }
   }
}
Copy after login

Output

Note: VectClass.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Elements of the unsorted list: 
97 93 95 99 82 88 
Elements of the newly sorted list: 
99 97 95 93 88 82 
Copy after login

Example 2

In this example, first, we will create a Comparator and inside it, we define our logic in 'compare()' method to sort the vector objects in descending order. The logic here states that take two objects at the same time and compare them using the if-else block. If first object is greater than second return -1 otherwise 1. Then, we pass the object of comparator to 'Collection.sort()' for sorting operation.

import java.util.*;
public class VectClass {
   public static void main(String args[]) {
      // Using comparator interface for sorting
      Comparator<Integer> comp = new Comparator<Integer>() {
         // logic to sort in descending order
         public int compare(Integer i, Integer j) {
            if(i < j) {
               return 1;
            } else {
               return -1;
            }
         }
      };
      // Creation of vector 
      Vector<Integer> vectList = new Vector<>();
      // Adding elements in the vector
      vectList.add(97);
      vectList.add(93);
      vectList.add(95);
      vectList.add(99);
      vectList.add(82);
      vectList.add(88);
      System.out.println("Elements of the unsorted list: ");
      // loop to iterate through elements
      for(int i = 0; i < vectList.size(); i++ ) {
         // to print the elements of the vector
		   System.out.print(vectList.get(i) + " "); 
      }
      System.out.println();
      Collections.sort(vectList, comp); // sort using comparator
      System.out.println("Elements of the newly sorted list: ");
      // loop to iterate through elements
      for(int i = 0; i < vectList.size(); i++ ) {
         // to print the elements of the new vector
         System.out.print(vectList.get(i) + " "); 
      }
   }
}
Copy after login

Output

Elements of the unsorted list: 
97 93 95 99 82 88 
Elements of the newly sorted list: 
99 97 95 93 88 82 
Copy after login

in conclusion

This article has explained the implementation of the Comparator Interface and also we discovered the use of a few inbuilt methods such as 'compareTo()', 'Collection.sort()' and 'Collections.reverseOrder()'.

The above is the detailed content of Sort Java vectors in descending order using comparator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!