Kebab Programmer
Kebab Programmer

Reputation: 1219

How to sort Objects in an Arraylist with an Object parameter

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?

Upvotes: 1

Views: 28959

Answers (5)

Beyhan
Beyhan

Reputation: 99

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));

Upvotes: 0

Sachindra N. Pandey
Sachindra N. Pandey

Reputation: 1252

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);
 }
}

Upvotes: 0

Wundwin Born
Wundwin Born

Reputation: 3475

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());
        }
    });

Upvotes: 9

ortis
ortis

Reputation: 2223

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.

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68915

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.

Upvotes: 0

Related Questions