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
How to Sort HashSet Elements using Comparable Interface in Java?
The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted. To sort HashSe
3 min read
How to Sort TreeSet Elements using Comparable Interface in Java?
TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a Set using their natural ordering whether an explicit comparator is provided. To sort TreeSet elements using Comparable interface in java first, we create a cl
3 min read
How to Sort LinkedHashSet Elements using Comparable Interface in Java?
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read
Finding Minimum And Maximum Element of Vector using Comparable Interface in Java
The Vector class in java implements a dynamic array i.e. it can grow and shrink according to the elements that we insert or remove to/from it. It implements the List interface so it supports all the methods provided by the List interface. In this article, we are going to discuss how we can find the
3 min read
How to Create TreeMap Objects using Comparable Interface in Java?
In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Co
6 min read
Sort Java Vector in Descending Order Using Comparator
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of the List interface. There are two types of Sorting t
3 min read
Sort LinkedHashMap by Values using Comparable Interface in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. Assuming you have gone through LinkedHashMap in java and know about LinkedHashMap. Syntax: int compare(T obj) ; Illustration: Input : { GEEKS=1, geeks=3, for=2 } Output : { GEEKS=1
2 min read
How to Iterate the Vector Elements in the Reverse Order in Java?
The Vector class is found in java.util package and it implements List interface. The Vector class is included in the java collection framework from Java version 1.2. Unlike arrays, vectors can grow and shrink their size, and thus they are also called the Dynamic Array. Vectors are synchronized, ie t
3 min read
Searching Elements in Vector Using Index in Java
Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. An element of a Vector can be searched using an index with different methods. Suppose if the element is not present in the Vector then th
4 min read
Iterate Over Vector Elements in Java
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. We can iterate over vector by the following ways: Simple for-loopEnhanced for-loopIteratorsEnumeration interface Method 1: Simple for-loop The idea is
4 min read