...

View Full Version : Sort java objects in an Array



rajeshnaidu
08-09-2004, 03:16 PM
I have an array of Java objects(for example: Employee). I need to sort this array based on any one of the data variable(for example: emp_name, desg, salary) in the Java class.

I had done using Comparable and Comparator interfaces. But the problem here is need to handle both ascending and descending dynamically based on parameter passed.

Can anyone help me in this?

Thanking you in advance.

VietBoyVS
08-09-2004, 05:48 PM
You're on the right track, you have to use compareTo inside your Comparator class that you create.

you have to have the compare( ) method this is where how you want to sort it.

hrk2006
08-27-2004, 09:53 AM
I think this code might be helpful




Sort java objects in an Array

Sorting in Java is Easy!
Author: vglass@jfind.com, Van Glass
There once was a time that sorting an array of primitives in Java took some work. And sorting an array of Objects involved even more. Nowadays we can sort arrays of primitives and Objects with relatively little code using the Comparable interface.
The java.util.Comparable interface is a class which when implemented will define the natural order for a pair of Objects. Currently there are only a handful of classes which by default implement the Comparable interface. One such class is the String class. In implementing the Comparable interface the String class overloads the compareTo(Object obj) method. The compareTo(Object obj) method returns a negative integer, zero, or a positive integer where the current instance is less than, equal to, or greater than object received.
The work has already been done for us in the String class. However if you want to provide sorting capabilities for your own classes then you must implement Comparable and overload the compareTo(Object obj) yourself. Here is a simple example which defines a class Student. Each Student has a studentid, first_name, last_name. According to our specifications Student should be sorted by student_id.
import java.util.*;

public class Student implements Comparable
{
public int student_id;
public String last_name;
public String first_name;

public Student(int student_id, String last_name, String first_name)
{
this.student_id = student_id;
this.last_name = last_name;
this.first_name = first_name;
}

/* Overload compareTo method */

public int compareTo(Object obj)
{
Student tmp = (Student)obj;
if(this.student_id < tmp.student_id)
{
/* instance lt received */
return -1;
}
else if(this.student_id > tmp.student_id)
{
/* instance gt received */
return 1;
}
/* instance == received */
return 0;
}

}
Now that the Student class overloads the compareTo(Object obj) method we can easily sort an array of Student objects. This is done using the java.util.Array class and its static sort method. A main method has been added below to demonstrate how this would work.
public static void main(String[] args)
{
/* Create an array of Student object */

Student[] students = new Student[3];
students[0] = new Student(52645,"Smith","Bob");
students[1] = new Student(98765,"Jones","Will");
students[2] = new Student(1354,"Johnson","Matt");

/* Sort array */
Arrays.sort(students);

/* Print out sorted values */

for(int i = 0; i < students.length; i++)
{
System.out.println(students[i].student_id +
students[i].last_name + students[i].first_name);
}
}
Simple right? With a little more work the Student class could be modified to sort on a combination of member variables. For instance you may want to sort first by last_name and then by student_id. Keep in mind that the Arrays class will sort any array including an array of primitives. With primitives however there is no need to implement Comparable making it very easy to sort int, float etc. Until next week.

ctbalamurali
10-20-2008, 06:47 PM
Dynamic variable can be passed to determine the the sorting order
Please find the updated sample code. Thanks


Sample code:

Camparable Object:
[PHP]package Sorting;

public class Student implements Comparable {
public Long student_id;

public String last_name;

public String first_name;

public boolean isAsc;

public Student(Long student_id, String last_name, String first_name, boolean isAsc) {
this.student_id = student_id;
this.last_name = last_name;
this.first_name = first_name;
this.isAsc = isAsc;
}

/* Overload compareTo method */

public int compareTo(Object obj) {
Student tmp = (Student) obj;

if (tmp.isAsc == true) {
if (this.student_id.compareTo(tmp.student_id) < 0) {
/* instance lt received */
return -1;
} else if (this.student_id.compareTo(tmp.student_id) > 0) {
/* instance gt received */
return 1;
}
} else // Desending
{
if (this.student_id.compareTo(tmp.student_id) > 0) {
/* instance gt received */
return -1;
} else if (this.student_id.compareTo(tmp.student_id) < 0) {
/* instance lt received */
return 1;
}
}

return 0;

}

}

It's main method:

package Sorting;

import java.util.Arrays;

public class SortMain {
public static void main(String[] args)
{
/* Create an array of Student object */

Student[] students = new Student[3];
students[0] = new Student(new Long (52645),"Smith","Bob",true);
students[1] = new Student(new Long (98765),"Jones","Will",true);
students[2] = new Student(new Long (1354),"Johnson","Matt",true);

/* Sort array */
Arrays.sort(students);

/* Print out sorted values */

for(int i = 0; i < students.length; i++)
{
System.out.println(students[i].student_id +
students[i].last_name + students[i].first_name);
}

// Desendig

/* Create an array of Student object */
students[0] = new Student(new Long (52645),"Smith","Bob",false);
students[1] = new Student(new Long (98765),"Jones","Will",false);
students[2] = new Student(new Long (1354),"Johnson","Matt",false);

/* Sort array */
Arrays.sort(students);

/* Print out sorted values */

for(int i = 0; i < students.length; i++)
{
System.out.println(students[i].student_id +
students[i].last_name + students[i].first_name);
}
}

}

shyam
10-21-2008, 06:28 PM
I had done using Comparable and Comparator interfaces. But the problem here is need to handle both ascending and descending dynamically based on parameter passed.
what did you do? the scenario you describe can be pretty easily accomplished using just comparator...(its usually easier to sort it ascending and reverse the results for descending >).. )


Dynamic variable can be passed to determine the the sorting order
Please find the updated sample code.

package Sorting;

public class Student implements Comparable {
public Long student_id;
public String last_name;
public String first_name;
public boolean isAsc;
...

}

cmon...this isn't passing a dynamic variable :O...have you considered the case when an collection containing some students who want to be sorted ascending and others descending !!

ctbalamurali
10-21-2008, 08:05 PM
what did you do? the scenario you describe can be pretty easily accomplished using just comparator...(its usually easier to sort it ascending and reverse the results for descending >).. )


cmon...this isn't passing a dynamic variable :O...have you considered the case when an collection containing some students who want to be sorted ascending and others descending !!

while craeting the student object in rn=untime sorting order need to be passed. once it order is passed then it will get sorted what ever the way it wants. This is called dynamic variable sir

Fou-Lu
10-22-2008, 08:52 AM
You guys are thinking too hard :P
There are tons of ways to do this, from creating you're own sorts, you're own collections, and so forth. But the easiest ways are already built in.
You need to implement a Comparable interface (I'm using generics here, but you can do this without and using 1.4), and make use of the Collections object:
Please note that my main is fluffed since I'm too lazy to create 15 employees by hand :P


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;


public class Employee implements Comparable<Employee>
{
private int iEmpNum;
private String sFName;
private String sLName;

public Employee(int iEmpNum, String sFName, String sLName)
{
this.iEmpNum = iEmpNum;
this.sFName = sFName;
this.sLName = sLName;
}

public String toString()
{
return "Employee[iEmpNum=" + this.iEmpNum + ", sFName=" + this.sFName +
", sLName=" + this.sLName + "]";
}

@Override
public int compareTo(Employee argv)
{
return this.iEmpNum - argv.iEmpNum;
}


public static void main(String[] argv)
{
int iNumEmployees = 15;
Employee[] aEmployee = new Employee[iNumEmployees];
ArrayList<String> alFNames = new ArrayList<String>();
alFNames.add("Kevin");
alFNames.add("John");
alFNames.add("Jane");
alFNames.add("Allison");

ArrayList<String> alLNames = new ArrayList<String>();
alLNames.add("Smith");
alLNames.add("Doe");
alLNames.add("Johnson");
alLNames.add("Thompson");

for (int i = 0; i < iNumEmployees; i++)
{
Collections.shuffle(alFNames);
Collections.shuffle(alLNames);
String sFName = alFNames.get(0);
String sLName = alLNames.get(0);
int iEmpNum = (int)(Math.random() * 100);
aEmployee[i] = new Employee(iEmpNum, sFName, sLName);
}

// Print unsorted.
System.out.println("Unsorted List: ");
for(Employee e:aEmployee)
{
System.out.println(e);
}

// Print sorted.
Arrays.sort(aEmployee);
System.out.println("\nSorted List: ");
for(Employee e:aEmployee)
{
System.out.println(e);
}

/**********************************************************************
* THIS IS WHAT MAKES IT RSORT
**********************************************************************/
Arrays.sort(aEmployee, Collections.reverseOrder());
System.out.println("\nReverse Sorted List: ");
for(Employee e:aEmployee)
{
System.out.println(e);
}
}
}



And Sample Output:


Unsorted List:
Employee[iEmpNum=31, sFName=John, sLName=Doe]
Employee[iEmpNum=26, sFName=Jane, sLName=Johnson]
Employee[iEmpNum=2, sFName=John, sLName=Thompson]
Employee[iEmpNum=74, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=48, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=70, sFName=John, sLName=Smith]
Employee[iEmpNum=7, sFName=Kevin, sLName=Smith]
Employee[iEmpNum=31, sFName=John, sLName=Johnson]
Employee[iEmpNum=18, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=2, sFName=John, sLName=Doe]
Employee[iEmpNum=41, sFName=Allison, sLName=Thompson]
Employee[iEmpNum=74, sFName=Kevin, sLName=Thompson]
Employee[iEmpNum=22, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=64, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=80, sFName=Allison, sLName=Smith]

Sorted List:
Employee[iEmpNum=2, sFName=John, sLName=Thompson]
Employee[iEmpNum=2, sFName=John, sLName=Doe]
Employee[iEmpNum=7, sFName=Kevin, sLName=Smith]
Employee[iEmpNum=18, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=22, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=26, sFName=Jane, sLName=Johnson]
Employee[iEmpNum=31, sFName=John, sLName=Doe]
Employee[iEmpNum=31, sFName=John, sLName=Johnson]
Employee[iEmpNum=41, sFName=Allison, sLName=Thompson]
Employee[iEmpNum=48, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=64, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=70, sFName=John, sLName=Smith]
Employee[iEmpNum=74, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=74, sFName=Kevin, sLName=Thompson]
Employee[iEmpNum=80, sFName=Allison, sLName=Smith]

Reverse Sorted List:
Employee[iEmpNum=80, sFName=Allison, sLName=Smith]
Employee[iEmpNum=74, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=74, sFName=Kevin, sLName=Thompson]
Employee[iEmpNum=70, sFName=John, sLName=Smith]
Employee[iEmpNum=64, sFName=Kevin, sLName=Doe]
Employee[iEmpNum=48, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=41, sFName=Allison, sLName=Thompson]
Employee[iEmpNum=31, sFName=John, sLName=Doe]
Employee[iEmpNum=31, sFName=John, sLName=Johnson]
Employee[iEmpNum=26, sFName=Jane, sLName=Johnson]
Employee[iEmpNum=22, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=18, sFName=Allison, sLName=Johnson]
Employee[iEmpNum=7, sFName=Kevin, sLName=Smith]
Employee[iEmpNum=2, sFName=John, sLName=Thompson]
Employee[iEmpNum=2, sFName=John, sLName=Doe]


This kinda what you're looking for? Works great from you're main, all you need to do is ensure that compareTo exists through Comparable, and that you use Arrays.sort(yourstack, Collections.reverseOrder()). Simple as that :)

shyam
10-22-2008, 06:29 PM
while craeting the student object in rn=untime sorting order need to be passed. once it order is passed then it will get sorted what ever the way it wants. This is called dynamic variable sir

did you try this?


Student[] students = new Student[3];
students[0] = new Student(new Long (52645),"Smith","Bob",true);
students[1] = new Student(new Long (98765),"Jones","Will",false); // looks like Jones does not like being sorted in ascending :O
students[2] = new Student(new Long (1354),"Johnson","Matt",true);

/* Sort array */
Arrays.sort(students);

sorting as an operation should not have any dependency on the operands...Fou-lu has given the solution using the Comparable interface...Here's how you can do it using the Comparator interface (casting aside doubts whether rajeshnaidu has completed his homework :/ )


class StudentComparator implements Comparator<Student> {
boolean ascending = true;
public StudentComparator(boolean ascending) {
this.ascending = ascending;
}
public int compare(Student arg0, Student arg1) {
return ascending ? arg0.student_id.compareTo(arg1.student_id) : arg1.student_id.compareTo(arg0.student_id);
}
}

...
// ascending
Arrays.sort(students, new StudentComparator(true));
//descending
Arrays.sort(students, new StudentComparator(false));

Fou-Lu
10-22-2008, 08:07 PM
Yep, IMO the comparator is the best solution.
The comparable works great if its always the same field that you plan on comparing. On the otherhand, you can do the comparator up as an abstract and extend it out to other properties; with my example you could do up an AbsEmpSorter and extend it up for EmpSorterID, EmpSorterFirstName and EmpSorterLastName. Since these are all typeof Comparator it works perfectly inside of the Arrays.sort method.
Another option is to create a collection for the Employee, either by extending a collection or simply holding an array of given values. I would extend the collection, I can't recall offhand if you need to override any of the sort or reverse functions, but I still like containing everything in objects instead of arrays. Combine the collections with comparable objects for it, and you've got one awesome sortable object, with an rsort built in!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum