Thiago Valentim
Thiago Valentim

Reputation: 520

Sort a collection of objects in Java with comparable interface

It is possible to sort a collection of objects with comparable interface and when you find some attribute equal increment value?

I need to keep a collection ordered by a numeric attribute, identify attributes and increase equal value without losing the ordering

Upvotes: 1

Views: 206

Answers (1)

Amar Wadhwani
Amar Wadhwani

Reputation: 67

Based on the limited description in the question, you can try with the following code:

class Student implements Comparable < Student >
{
  int rollno;
  String name;
  int age;
  Student (int rollno, String name, int age)
  {
    this.rollno = rollno;
    this.name = name;
    this.age = age;
  }

  public int compareTo (Student st)
  {
    if (age == st.age)
      {
        st.age += 1;
        return -1;
      }

    else if (age > st.age)
      return 1;
    else
      return -1;
  }
}

When you run this code with the following, you get the desired output :

Executing Code:

public static void main (String[]args)
  {
    ArrayList < Student > al = new ArrayList < Student > ();
    al.add (new Student (101, "Vijay", 23));
    al.add (new Student (106, "Ajay", 23));
    al.add (new Student (105, "Jai", 21));

    Collections.sort (al);
    for (Student st:al)
      {
        System.out.println (st.rollno + " " + st.name + " " + st.age);
      }
  }

Output:

105 Jai 21
106 Ajay 23
101 Vijay 24

Upvotes: 1

Related Questions