2
class Person 
 {
 private String name;
 private String profession;
}

profession has values:

  • engineer
  • Doctor
  • Teacher
  • student

I have list of person and want to sort it on the basis of Profession. engineer comes first then Doctor and then Teacher and then student.

Is it possible to sort it with comparable interface.

5
  • What is your sorting logic. I think Engineer>Doctor>Teacher>Student is not possible for String Commented May 7, 2015 at 12:18
  • 1
    maybe if profession was an enum... Commented May 7, 2015 at 12:20
  • there is a default string function which sort according to alphabets Commented May 7, 2015 at 12:22
  • [You can refer my answer from this question which is somewhat like this][1] [1]: stackoverflow.com/questions/29777696/… Commented May 7, 2015 at 12:35
  • I vote for enum since it can be easily compared directly without any kind of mapping to weight values. Commented May 7, 2015 at 12:40

7 Answers 7

1

You can sort your custom object using Collection.sort method like this,

Collections.sort(list, new Comparator(){

        public int compare(Object o1, Object o2) {
            Person p1 = (Person) o1;
            Person p2 = (Person) o2;
            return p1.getProfession().compareToIgnoreCase(p2.getProfession());
        }

    });

To Sort in reverse order just make your return statement line like this,

p2.getProfession().compareToIgnoreCase(p1.getProfession());

This will directly make your list sorted.

Sign up to request clarification or add additional context in comments.

1 Comment

by this, engineer will stand after doctor, when it needs to stand behind.
1

Add enum to your variables:

class Person {
   private String name;
   private String profession;
   private enum enumProffesion
    {
        Doctor, Teacher, student;
    }
}

After that could add function to the Person class which would give you value of the profession:

public int professionValue()
{
    enumProffesion enumValue= enumProffesion.valueOf(proffesion);
    switch (enumValue) {
    case Doctor: return 1; break;
    case Teacher: return 2; break;
    case student: return 3; break;
    default: return null;
    }
}

After that you just implement logic that will sort all Persons. For that you can help your self with this answer: sorting integers in order lowest to highest java

7 Comments

No need of such mapping, you can compare enum instances directly. (e. g. EnumProfession.DOCTOR.compareTo(EnumProfession.TEACHER)) Order will be that on which values were defined.
I tried: pastebin.com/QnqXffmJ And if you compare Teacher to Student you get : -1 and if you compare you also get: -1 So if you would try to sort it like I proposed in step 2you couldn't do it. But you could it a little bit diffrent.
If I try my solution: pastebin.com/ufbWZkVw I get this values: System.out.println(professionValue("Doctor")); output: 1 System.out.println(professionValue("Teacher")); output: 2 System.out.println(professionValue("student")); output: 3
I like your post because no one else proposed enums, but some mapping or alphabetical sort (which became broken when engineer was added). But it really doesn't need such ugly mapping. See here: docs.oracle.com/javase/8/docs/api/java/lang/…
so if you compare teacher to student by your mapping, you'll also get -1. So everything is okay.
|
1

Implement Comparable

Yes you can implement Comparable. Create a method compareTo(Person obj) and then write your custom logic. You can compare alphabetically or whatever other algorithm you want - for example engineer before doctor because he makes more money :) For alphabetic comparing you can do it like that:

class Person implements Comparable<Person> {

@Override
public int compareTo(Person o) {
    return this.profession.compareTo(o.getProfession());

  }
  private String name;
  private String profession;
}

After that you just use the Collections.sort

Comments

1

Enum

You can do it easily if replace profession field by enum:

class Person implements Comparable<Person> {
    private String name;
    private Profession profession;

    // by this we'll define natural ordering based on ordering
    // in which `Profession` enum values are declared
    @Override
    public int compareTo(Person p) {
        return this.profession.compareTo(p.profession);
    } 
}

And here's Profession enum:

public enum Profession {
    ENGINEER("engineer"), DOCTOR("Doctor"), TEACHER("Teacher"), STUDENT("student");
    
    private String displayName;
    
    Profession(String dn) {
        this.displayName = dn;
    }

    @Override
    public String toString() {
        return this.displayName;
    }
}

If you are new to the enum facility in Java, see Oracle tutorial.

1 Comment

I edited your good example code to use the displayName style of naming used in the JDK's classes such as DayOfWeek
0

Add getter and setter for profession in Person class and simply use below code

class Person {
   private String name;
   private String profession;
   public String getProfession() {  
        return profession;  
    }  
    public void setProfession(String profession) {  
        this.profession = profession;  
    }
}


List<Person> personList = new ArrayList<Person>(); 

Person p1 = new Person();
p1.setProfession("Engineer"); 
personList.add(p1);

Person p2 = new Person();
p2.setProfession("Doctor"); 
personList.add(p2);

Person p3 = new Person();
p3.setProfession("Teacher"); 
personList.add(p3);

Person p4 = new Person();
p4.setProfession("student"); 
personList.add(p4);


Collections.sort(personList, new Comparator() {  
@Override  
public int compare(Object obj1, Object obj2) {  
Person p1 = (Person)obj1;  
Person p2 = (Person)obj2;  
return p1.getProfession().compareToIgnoreCase(p2.getProfession());  
}  
});

Comments

0

Two ways:

  1. Implement the Comparable interface
  2. Create a Comparator

With the first way you can sort the collection only by the one method compareTo you will define

Your Person.java

class Person implements Comparable<Person> {
    private String name;
    private String profession;

    @Override
    public int compareTo(Person o) {
        return this.profession.compareTo(o.getProfession());
    }

    public String getName() {
        return name;
    }

    public String getProfession() {
        return profession;
    }
}

Then you need to call:

Collections.sort(yourCollection);

With the second way you can sort by one or more Comparator, giving you the ability to compare the same collection with different criteria.

Example of two Comparator

public class PersonSortByNameComparator implements Comparator<Person>{

    @Override
    public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }

}

public class PersonSortByAlphabeticalProfessionComparator implements Comparator<Person>{

    @Override
    public int compare(Person p1, Person p2) {
        return p1.getProfession().compareTo(p2.getProfession());
    }

}

Or this one you need:

public class PersonSortByProfessionComparator implements Comparator<Person> {

    @Override
    public int compare(Person p1, Person p2) {
        if(p1.getProfession().equalsIgnoreCase(p2.getProfession())
            return 0;
        if(p1.getProfession().equalsIgnoreCase("student")
            return -1;
        if(p1.getProfession().equalsIgnoreCase("engineer")
            return 1;
        if(p1.getProfession().equalsIgnoreCase("doctor")
            return 1;
        else
            return -1;
    }
}

And then call one of them:

Collections.sort(yourCollection, new PersonSortByNameComparator());

This blog article is really good written and you can some examples

Comments

0

My suggestion -

1. Create a new class Profession -

class Profession{

   public Profession(Integer id, String prefessionName){
      this.id=id;
      this.prefessionName=prefessionName;
   }
   Integer id;
   String professionName;

}  

2. Now give Id to each Profession object/instance maintaining the order. For example -

   Profession engineer = new Profession(1, "Engineer"); //since Engineer is in first place 
   Profession doctor = new Profession(2, "Doctor"); //since Doctor is in second place
   Profession teacher = new Profession(3, "Teacher");
   Profession student = new Profession(4, "Student");

3. Now sort the Profession for id using compareable interface.

2 Comments

He probably forgot to change Doctor to 2, Teacher to 3 and Student to 4 when he was copying code...
Thanks. It was a typos, which I have just fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.