Java Topics
HubJava Collections FrameworkCollections Practice ProgramsComparable vs ComparatorGenericsIteratorArrayListLinkedListStackVectorHashMapHashtableLinkedHashMapTreeMapArrayDequeDeque Double-Ended QueuePriorityQueueHashSetLinkedHashSetTreeSetAdapter PatternBuilder PatternFactory PatternMVC PatternObserver PatternSingleton PatternDynamic ProgrammingGraphHashingHeapLinked List DSAQueue DSARecursionSearching AlgorithmsSorting AlgorithmsStack DSATime ComplexityTreesException Handling Best PracticesCustom ExceptionException Hierarchyfinally BlockException Handlingthrow aur throwstry-catchBuffered StreamsByte StreamsCharacter StreamsDeserializationFile ClassJava NIO New I/OSerializationArrays in JavaArray OperationsArray Practice ProgramsArray Interview QuestionsJagged ArrayMulti-Dimensional ArraysOne Dimensional Arraybreak aur continuedo-while Loopfor Loopif-else StatementsNested Loopsswitch-case Statementwhile LoopJava Compilation ProcessJava ki FeaturesPehla Java ProgramHistory of JavaJava EditionsJava Program StructureJDK, JRE aur JVMJava Kya Hai?Immutable StringsString Class in JavaString Interview QuestionsString MethodsString Practice ProgramsStringBufferStringBuilderComments in JavaData Types in JavaIdentifiers in JavaInput & Output in JavaJava KeywordsOperators in JavaType Casting in JavaVariables in JavaJava Coding Interview QuestionsCollections Interview QuestionsCore Java Interview QuestionsJDBC Interview QuestionsMultithreading Interview QuestionsOOPs Interview QuestionsSpring Framework Interview QuestionsJava 8 Date/Time APIDefault aur Static Methods in InterfaceFunctional InterfaceLambda ExpressionMethod ReferenceOptional ClassStream APIBatch ProcessingCallableStatementJDBC ArchitectureJDBC — Java Database ConnectivityJDBC Practice ProjectsMySQL ConnectionPreparedStatementResultSetStatement InterfaceTransaction ManagementCreating ThreadsDaemon ThreadExecutor FrameworkInter-Thread CommunicationMultithreading Practice ProgramsRunnable InterfaceSynchronizationThread ClassMultithreading IntroductionThread Life CycleThread PriorityJava Cheat SheetImportant Formulas & Key ConceptsImportant Java ProgramsJava Quick RevisionAbstract ClassAbstractionAnonymous ClassClass and ObjectConstructorEncapsulationInheritanceInner ClassInterfaceMethod OverloadingMethod OverridingObject ClassObject CloningObject-Oriented Programming OOPPolymorphismstatic Keywordsuper Keywordthis KeywordWrapper ClassesArray Practice ProgramsBasic Java Practice ProgramsCollection Practice ProgramsJDBC Practice ProgramsMultithreading Practice ProgramsOOPs Practice ProgramsPlacement Coding QuestionsString Practice ProgramsBanking SystemChat ApplicationE-Commerce Backend — Spring Boot REST APIEmployee Management SystemLibrary Management SystemSpring Boot Fullstack ProjectStudent Management SystemCookies in ServletExpression Language ELGenericServletHttpServletJavaServer Pages JSPJSP TagsMVC ArchitectureHttpServletRequest & HttpServletResponseServlet IntroductionServlet Life CycleSession TrackingDependency InjectionSpring BeansSpring CoreSpring FrameworkAPI GatewaySpring Cloud Config ServerDocker DeploymentEureka Server — Service DiscoverySpring Boot CRUD ApplicationException Handling in Spring BootJWT AuthenticationREST API in Spring BootSpring SecuritySpring BootSpring Data JPAValidation in Spring Boot
Comparable vs Comparator
Last Updated : 26 May, 2026
title: Comparable vs Comparator
Collections Framework70 words3 headingsTables includedExamples included
title: Comparable vs Comparator description: Sorting order define karne ke do tarike
Comparable — Natural Ordering
Class khud sorting define karta hai. java.lang.Comparable implement karo.
java exampleWoHoTech
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public int compareTo(Student other) {
return this.marks - other.marks; // Marks ke hisaab se sort
// Negative: this < other
// Zero: equal
// Positive: this > other
}
}
List<Student> students = new ArrayList<>();
students.add(new Student("Ram", 85));
students.add(new Student("Shyam", 92));
students.add(new Student("Geeta", 78));
Collections.sort(students); // Uses compareToComparator — Custom Ordering
Bahar se custom sort logic define karo.
java exampleWoHoTech
// By name
Comparator<Student> byName = Comparator.comparing(s -> s.name);
// By marks descending
Comparator<Student> byMarksDesc = Comparator.comparingInt(Student::getMarks).reversed();
// Multiple fields
Comparator<Student> multi = Comparator.comparingInt(Student::getMarks)
.thenComparing(s -> s.name);
Collections.sort(students, byName);
Collections.sort(students, byMarksDesc);
students.sort(multi);Comparator vs Comparable
| Comparable | Comparator | |
|---|---|---|
| -- | -- | -- |
| Package | java.lang | java.util |
| Method | compareTo() | compare() |
| Class modification | Required | Not required |
| Sort orders | One (natural) | Multiple possible |
| Use | Default sort | Custom sort |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Comparable vs Comparator.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java topic.
Search Terms
java, java programming, core java, java master course, java notes, master, course, collections
Related Java Topics
Continue learning this concept
Collections FrameworkJava Collections Frameworktitle: Collections Framework OverviewCollections FrameworkCollections Practice Programstitle: Collections ProgramsCollections FrameworkGenericstitle: Generics in JavaCollections FrameworkIteratortitle: Iterator in JavaCollections FrameworkArrayListtitle: ArrayList in JavaCollections FrameworkLinkedListtitle: LinkedList in Java