1

I am having problems with sorting objects in an Arraylist as I am new to sorting object.

Sorting an arraylist is pretty basic, but sorting an arraylist of objects is a completely different matter. Basically I have been going over code here in stack overflow and people seem to use comparators to solve their problems, but they don't explain how to actually call the method and put it into use, and that is why I am here.

With the code below I am trying to sort an arraylist of Students with parameters - String name, int age and string course. I then have another class to store Student objects and sort them within the class. Here is what I have :

Student.java

public class Student {

    private String name, course;
    private int age;

    public Student(String name, int age, String course) {
        this.name = name;
        this.age = age;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCourse() {
        return course;
    }
}

CompareObj.java

import java.util.*;

public class CompareObj implements Comparator<Student>{

    private ArrayList<Student> sList;

    public CompareObj() {
        sList = new ArrayList<Student>();
    }

    @Override
    public int compare(Student s1, Student s2) {
         return s2.getName().compareTo(s1.getName());
    }

    public void add(Student s1) {
        sList.add(s1);
    }

    public void displayList() {
        for(int i = 0; i<sList.size();i++) {
            System.out.println(sList.get(i).getName());
        }
    }
}

In CompareObj class, how can I use the implemented method compare(s1,s2), how can I use this method to sort my arraylist of student objects?

1
  • Have you looked at the JavaDoc for the Collections class? There's a static method there: Collections#sort(List<T>, Comparator<? super T>). Commented Aug 14, 2014 at 15:16

5 Answers 5

9
how can i use this method to sort my arraylist of student objects?

You don't need to call compare() yourself. You can just pass your comparator to Collections.sort() that will take care sorting for you by calling compare() method.


By using custom class CompareObj,

Collections.sort(studentList, new CompareObj());

Or another way without CompareObj is,

Collections.sort(studentList,new Comparator<Student>() {
         @Override
        public int compare(Student s1, Student s2) {
                return s1.getName().compareToIgnoreCase(s2.getName());
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

This worked Fantastically, i remove "implements Comparator<Student>" and added in the second part of the code and it sorted my list perfectly
@ProgrammingNewb In CompareObj class, try with compareToIgnoreCase() instead of compareTo(), and in fact no need to initialize student list in its constructor. In that class you need only implementation of compare() method :)
You could also implement Comparable and its compareTo method on the Student class and call the single-argument form of Collections.sort.
As i said the second part of your answer worked just fine, and i am happy that i can now sort out objects in an arraylist, thanks for your input :)
1

Your class CompareObj is mixing both ArrayList (by encapuslation) and Comparator (by implenting interface). You don't need that, implementing Comparator is enough.

Try the following:

ArrayList<Strudent> students = new ArrayList<Student>();

// fill the ArrayList...

Collections.sort(students, new CompareObj());

This will sort student by their name, as specified in your CompareObj class.

2 Comments

You know for "Collections.sort(students, new CompareObj());" does it create a new sorted instance of the student list?
No it does not. It will change the order of the ArrayList passed in parameters.
0

You can use Arrays.sort() method

Arrays.sort(studentArray, new CompareObj ());

However if you think name is a way of naturally ordering Students then make your Student class implement Comparable interface and override compareTo() method.

2 Comments

I understand your point, because i know i can use both the Comparable interface class and i can use the Comparator interface class, but my question is how do i use these methods, more specifically, how do i call the methods, so that they can sort my list of objects?
If you are using Comparable interface then you need to call Arrays.sort(studentArray). If you are defining your own comparator you can use that as second argument as described in my answer.
0

Example to sort element in ArrayList

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListSorting {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    ArrayList al=new ArrayList<>();
    al.add("a");
    al.add("b");
    al.add("c");
    al.add("d");
    al.add("e");

    System.out.println("Before sorting");
    System.out.println(al);
    Collections.sort(al,new ArrayCustomizedSorting());
    System.out.println("After  sorting");
    System.out.println(al);
 }

}

 class ArrayCustomizedSorting implements Comparator<String>{

  @Override
  public int compare(String o1, String o2) {
    // TODO Auto-generated method stub
    return -o1.compareTo(o2);
 }
}

Comments

0

You can use array sort algorithms for that.

//Convert arraylist to array
ZAATSAYIM[] a = jsonResultWrapper.sayimDTOs.toArray(
                new ZAATSAYIM[jsonResultWrapper.sayimDTOs.size()]);

        //By date
        Date date1, date2;

        boolean sorted = false;
        ZAATSAYIM temp;
        while (!sorted) {
            sorted = true;
            for (int i = 0; i < a.length - 1; i++) {

                date1 = a[i].getCDATETIMEDAte();
                date2 = a[i + 1].getCDATETIMEDAte();

                int diff = date2.compareTo(date1);
                boolean after = (diff > 0);
                boolean isSame = (diff == 0);
                if (after) {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    sorted = false;
                } else if (isSame && (a[i].getSignlaStregthInt() < a[i + 1].getSignlaStregthInt())) {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    sorted = false;
                }
            }
        }

        jsonResultWrapper.sayimDTOs = new ArrayList<ZAATSAYIM>(Arrays.asList(a));

Comments

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.