Fetching the code, complexity notes and tags. Just a moment.
This snippet demonstrates two common ways to sort custom objects in Java: using the Comparable interface for natural ordering and the Comparator interface for custom sorting. Comparable is ideal when a class has a default sorting order, while Comparator provides flexibility to sort objects based on different fields. This is one of the most frequently asked Java interview concepts.
Category
oop
Complexity
Time: O(n log n) | Space: O(1)
Language
Java
Status
Tags
Related Concepts
Published
Last Updated
Production-ready Java implementation for quick revision, interview preparation, and real-world development.
Solution.java
1import java.util.ArrayList;2import java.util.Collections;3import java.util.Comparator;4 5class Student implements Comparable<Student> {6 7 int id;8 String name;9 double marks;10 11 public Student(int id, String name, double marks) {12 this.id = id;13 this.name = name;14 this.marks = marks;15 }16 17 @Override18 public int compareTo(Student other) {19 return this.name.compareTo(other.name);20 }21 22 @Override23 public String toString() {24 return id + " | " + name + " | " + marks;25 }26}27 28public class ComparableComparatorExample {29 30 public static void main(String[] args) {31 32 ArrayList<Student> students = new ArrayList<>();33 34 students.add(new Student(101, "Rahul", 85.5));35 students.add(new Student(102, "Ankit", 92.0));36 students.add(new Student(103, "Priya", 78.5));37 students.add(new Student(104, "Sneha", 88.0));38 39 Collections.sort(students);40 41 System.out.println("Sorted by Name:");42 43 for (Student student : students) {44 System.out.println(student);45 }46 47 students.sort(Comparator.comparingDouble(student -> student.marks));48 49 System.out.println("\nSorted by Marks:");50 51 for (Student student : students) {52 System.out.println(student);53 }54 }55}Keywords
Explore the important concepts and keywords associated with this Java snippet.
💡 These tags help you quickly identify the concepts covered in this snippet and make it easier to discover similar Java solutions throughout the library.