1

I'm trying to sort out the array by last name, and i've hit a brick wall in my code, i don't know what to do, and i can't find anything that helps me. My main problem is in

     public void sortByLastName(){
         Collections.sort(list);
     }

These two pieces of code are in two different classes, is that a problem?

    public int compareTo(Person p){
    int compareResult = this.lastName.compareTo(p.lastName);
    if(compareResult == 0){
        return 0;
    }
        else
            if(compareResult > 0){
                return 1;
            }
            else
                return -1;
    }
}
2
  • 2
    this can be rewritten to return this.lastName.compareTo(p.lastName); Commented Mar 26, 2013 at 0:23
  • 1
    Assuming that lastName is a string, you can do this: return this.lastName.toLower().compareTo(p.lastName.toLower()); and save yourself all the rest of the code. The compare in string is a case-sensitive one, though, so be careful. Commented Mar 26, 2013 at 0:24

4 Answers 4

3

If you ever desire to sort anything in more than one way, you will quickly determine that the best thing to do is to pass your comparison function as an argument to Collections.sort.

public void sortByLastName(){
    Collections.sort(list, new Comparator<Person>() {
        public int compare(Person lhs, Person rhs){
            return lhs.lastName.compareTo(rhs.lastName);
        }
    } );
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try:

public int compareTo(Person p){
    return lastName.compareToIgnoreCase(p.lastName);
}

Comments

0

Your compareTo method needs to be in your Person class. Your Person class needs to implement Comparable<Person>. Collections.sort will then work -

private static final class Person implements Comparable<Person> {

    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int compareTo(Person o) {
        int c = getLastName().compareTo(o.getLastName());
        if (c != 0) {
            return c;
        }
        return getFirstName().compareTo(o.getFirstName());
    }

    @Override
    public String toString() {
        return getFirstName() + " " + getLastName();
    }

}

public static void main(String[] args) {
    final List<Person> people = new LinkedList<Person>();
    people.add(new Person("John", "Smith"));
    people.add(new Person("Hans", "Mustermann"));
    people.add(new Person("John", "Doe"));
    System.out.println(people);
    Collections.sort(people);
    System.out.println(people);
}

Output:

[John Smith, Hans Mustermann, John Doe]
[John Doe, Hans Mustermann, John Smith]

Comments

-1

I've made ​​a function to sort a list of objects by a specific variable in the model class. It may not directly match the one you need, but maybe you can take the idea. I'm using reflection to be able to sort any class models with any data type.

 public Vector sort(Vector list, String kelas, String s, String asc) throws NoSuchMethodException {

        try {
            // Creates an object of type Class which contains the information of
            // the class String
            Object[] obj = list.toArray();
            Object[] args = {};
            Class cl = Class.forName(kelas);
            Method toSort = cl.getMethod(s, null);
            if (asc.equalsIgnoreCase("desc")) {
                if (toSort.getReturnType().toString().equalsIgnoreCase("int") || toSort.getReturnType().toString().equalsIgnoreCase("double")) {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (Double.parseDouble(toSort.invoke(obj[i], args).toString()) < Double.parseDouble(toSort.invoke(obj[j], args).toString())) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (toSort.invoke(obj[i], args).toString().compareToIgnoreCase(toSort.invoke(obj[j], args).toString()) < 0) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            } else {
                if (toSort.getReturnType().toString().equalsIgnoreCase("int") || toSort.getReturnType().toString().equalsIgnoreCase("double")) {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (Double.parseDouble(toSort.invoke(obj[i], args).toString()) > Double.parseDouble(toSort.invoke(obj[j], args).toString())) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (toSort.invoke(obj[i], args).toString().compareToIgnoreCase(toSort.invoke(obj[j], args).toString()) > 0) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            }

            list = new Vector();
            for (int i = 0; i < obj.length; i++) {
                list.add(obj[i]);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

you can call that function as simple as this :

Vector sortedList=sort(UnsortedList, "bean.Items", "getItemName", "asc");

This line will sort my item list (item is a model class) based on Item Name ascending

1 Comment

This is not only slower than the Collections.sort method it is also messier. Furthermore it uses a Vector which is synchronized. This is not a good approach. -1.

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.