Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Rajesh Mishra
Rajesh Mishra

Posted on • Originally published atonlinetutorials.tech on

     

Sorting using Comparable in java with example

Table of Contents

Basic points about the comparable interface.

Comparable is an interface available in java.lang package, which provides single sorting(means we can sort either the basis of id or name at a time. Consider we have Employee class which contains fields name and id).

The Comparable interfacecontains compare() method. If we want to sort any collection of user-defined objects using comparable, our java class must need to implement Comparable interface and overridecompareTo(Object o) method.

Program to sort on the basis of the name using Comparable.

  • Define an Employee class which should implement Comparable interface and create two variables name and id.  Provide corresponding getter/setter and parameterized constructor. Here we are going to sort employee object on basis of Id.
  • Override compareTo () method and provide logic.
  • @Overridepublic int compareTo(Object o) {        Employee employee = (Employee) o;        String name = employee.name;        return this.name.compareTo(name);}
  • Override compareTo () method and provide logic.
  • Create a couple of employee object using parameterized constructor and add into list.
  • List emplist = new ArrayList();emplist.add(new Employee("John", 101));emplist.add(new Employee("Eric", 106));emplist.add(new Employee("Arya", 103));emplist.add(new Employee("Sansa", 105));emplist.add(new Employee("Cersei", 102));
  • Use Collections.sort(emplist) the method which will internally call the compareTo() method(Check here how String compareTo() method internally works in java). Here Collections is a class and sort() is a static method. Use Java 8 forEach() method and print the name and id.

Comparable example in java:

import java.util.ArrayList;import java.util.Collections;import java.util.List;class Employee implements Comparable { private String name; private int id; public Employee(String string, int i) {  this.name = string;  this.id = i; } public String getName() {  return name; } public void setName(String name) {  this.name = name; } public int getId() {  return id; } public void setId(int id) {  this.id = id; } @Override  public int compareTo(Object o) {  Employee employee = (Employee) o;  String name = employee.name;  return this.name.compareTo(name); }}public class SortingByNameUsingComprable { public static void main(String[] args) {  List emplist = new ArrayList();  emplist.add(new Employee("John", 101));  emplist.add(new Employee("Eric", 106));  emplist.add(new Employee("Arya", 103));  emplist.add(new Employee("Sansa", 105));  emplist.add(new Employee("Cersei", 102));  Collections.sort(emplist);  emplist.forEach(empolyee ->           System.out.println(empolyee.getName() + " " + empolyee.getId())); }}
Arya 103Cersei 102Eric 106John 101Sansa 105

Program to sort on the basis of the id using Comparable.

For sorting on basis of id we need to change compareTo() logic as below. The rest of the steps would be the same.

@Override public int compareTo(Object o) { Employee employee = (Employee) o; return this.getId() - employee.getId();}
import java.lang.reflect.Field;import java.util.*; class Employee implements Comparable {    String name;    int id;     public Employee(String string, int i) {        this.name = string;        this.id = i;    }     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public int getId() {        return id;    }     public void setId(int id) {        this.id = id;    }     @Override    public int compareTo(Object o) {        Employee employee = (Employee) o;        return this.getId() - employee.getId();     }} public class SortingByIdUsingComprable {    public static void main(String[] args) {        List emplist = new ArrayList();        emplist.add(new Employee("John", 101));        emplist.add(new Employee("Eric", 106));        emplist.add(new Employee("Arya", 103));        emplist.add(new Employee("Sansa", 105));        emplist.add(new Employee("Cersei", 102));         Collections.sort(emplist);        emplist.forEach(empolyee -> System.out.println(empolyee.getName() + "   " + empolyee.getId()));    }}
John 101Cersei 102Arya 103Sansa 105Eric 106


Learn more about collection in java

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Java Developer | Blogging | howtostartprogramming.in
  • Location
    United Kingdom
  • Work
    Senior Software Enginner
  • Joined

More fromRajesh Mishra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp