How to Sort Vector Elements using Comparable Interface in Java?
Last Updated :
02 Mar, 2022
Vector is a child interface of collection. If we want to represent a group of the individual objects as a single entity where duplicates are allowed and insertion order must be preserved then we should go for vector. It is a resizable or growable array. It implements a Serializable, Cloneable, and RandomAccess interface. Every method present in the vector is synchronized and hence vector object is thread-safe.
Comparable interface is used to order the objects of the user-defined class. This interface is present in java.lang' package and it contains only one method compareTo(object). But it provides only a single sorting sequence i.e we can sort elements on the basis of single data members.
compareTo() method
This method is used to compare the current object with the specified object, and it returns three values depending on the comparison of the two objects. Using Comparable interface we can sort the elements of String class objects, user-define class objects, and all wrapper class objects.
Syntax:
public int compareTo(Object obj);
Return Type: Integer value
- Negative value if and only if the first object has to come before the second object.
- Positive value if and only if the first object has to come after the second object.
- Zero if and only if the first object is equal to the second object.
Collections is a utility class present in java.util' package to define several utility methods for collection objects like sorting, searching and reversing, etc.
In order to sort elements of a list, the Collections class defines the two sort methods as follows:
- public static void sort(List l): To sort based on default natural sorting order. In this case, a list should contain a homogeneous object or comparable object otherwise we will get runtime exception also list should not contain null otherwise we will get NullPointerException.
- public static void sort(List l, Comparator c): To sort based on customized sorting orders.
Implementation:
Consider creating a custom class name Students which implements the comparable interface in which we get the id of each student. Inside the driver class, we create a vector of type student class, and then we can sort the vector elements using the comparable interface by comparing the students' id.
Example 1:
Java
// Java Program to Sort Vector Elements
// using Comparable Interface
// Importing Collections and Vector classes from
// java.util package
import java.util.*;
import java.util.Collections;
import java.util.Vector;
// Class 1
// Helper class
// Class implementing comparable interface
class Student implements Comparable<Student> {
// Declaring a variable
private int id;
// Initializing the above variable through
// self constructor of this class
public Student(int id)
{
// 'this' keyword refers to current object itself
this.id = id;
}
// Converting the above Integer variable to String
public String toString()
{
return "Student[" + this.id + "]";
}
// Getting the 'id'
public int getId() { return this.id; }
// Comparing the ids of two student
// using the compareTo() method
public int compareTo(Student otherStudent)
{
return this.getId() - otherStudent.getId();
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of Vector type
// Declaring object of Student(user-defined type)
Vector<Student> student = new Vector<>();
// Adding student id to vector
// Custom input elements
student.add(new Student(1));
student.add(new Student(2));
student.add(new Student(9));
student.add(new Student(4));
student.add(new Student(34));
// Print all the elements
// before sorting
System.out.println(student);
// Calling sort() method of collections
Collections.sort(student);
// Print all the elements
// after sorting
System.out.println(student);
}
}
Output[Student[1], Student[2], Student[9], Student[4], Student[34]]
[Student[1], Student[2], Student[4], Student[9], Student[34]]
Example 2: student name, marks, and id in which we are going to sort the vector on the basis of student marks
Java
// Java Program to Sort Vector Elements
// using Comparable Interface
// Importing Collection an Vector classes from
// java.util package
import java.util.Collections;
import java.util.Vector;
import java.util.*;
// Class 1
// Helper class
// Class implementing comparable interface
class Student implements Comparable<Student> {
// // Declaring a variables- student name , marks and id
String name;
int marks;
int id;
// Initializing the above variable through
// self constructor of this class
public Student(String name,int marks,int id) {
// 'this' keyword refers to current object itself
this.name=name;
this.marks=marks;
this.id=id;
}
// Getting the 'id'
public int getMarks(){
return this.marks;
}
// Comparing the ids of two student
// using the compareTo() method
public int compareTo(Student otherStudent) {
return this.getMarks()-otherStudent.getMarks();
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args) {
// Creating an object of Vector type
// Declaring object of Student(user-defined type)
Vector<Student> student= new Vector<>();
// Adding student id to vector
// Custom input elements
student.add(new Student("Roshan",86,1));
student.add(new Student("Ritik",96,2));
student.add(new Student("Ashish",99,4));
student.add(new Student("Sandeep",100,9));
student.add(new Student("Piyush",88,34));
// Iterate over the sorted vector
// using for each loop
// before calling sort() method
for(Student s : student)
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
// New line
System.out.println() ;
// Calling sort() method of collections
Collections.sort(student);
// Iterate over the sorted vector
// using for each loop
// after calling sort() method
for(Student s : student)
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
}
}
OutputName:Roshan->Marks:86->ID:1
Name:Ritik->Marks:96->ID:2
Name:Ashish->Marks:99->ID:4
Name:Sandeep->Marks:100->ID:9
Name:Piyush->Marks:88->ID:34
Name:Roshan->Marks:86->ID:1
Name:Piyush->Marks:88->ID:34
Name:Ritik->Marks:96->ID:2
Name:Ashish->Marks:99->ID:4
Name:Sandeep->Marks:100->ID:9
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read