Java Comparable

Java Comparable interface belongs to java.lang package.

Comparable interface allows us to sort arrays and collections.

For custom sorting Comparable interface needs to implement and override compareTo(Object obj) method within the same bean class.

Arrays and Collections class internally implements Comparable interface as shown in below example.



NOTE: String and Wrapper classes by default implement the Comparable interface. Objects of String or wrapper classes in a list, set or map by default Comparable.

Sort Custom class object collection:

Bean class needs to implement Comparable interface and override compareTo() method.

Below Student bean class is implementing Comparable interface and overridden compareTo() method for sorting Student collection depending on the bean class name field.



Before Sorting = [Student{id=1, name=’Saurabh’, branch=’EN’}, Student{id=2, name=’Prabjot’, branch=’IT’}, Student{id=3, name=’Nitin’, branch=’ECE’}]
After Sorting By Name = [Student{id=3, name=’Nitin’, branch=’ECE’}, Student{id=2, name=’Prabjot’, branch=’IT’}, Student{id=1, name=’Saurabh’, branch=’EN’}]

Difference Between Comparable and Comparator

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan