Sort object array based on one object variable?
in
Programming Questions
•
3 years ago
I have an array of objects, each of which has a number of variables.
I would like to select the "top 20" objects, based on a specific variable.
I think this is really a version of the question: "How can I sort an object array based on a specific object variable?"
So I think that I can provide a simplified example of my question. Assume the following code:
Employee[] employees;
void setup() {
employees = new Employee[3];
employees[0] = new Employee(0,20000.00);
employees[1] = new Employee(1,40000.00);
employees[2] = new Employee(2,30000.00);
}
class Employee {
String firstName;
String lastName;
int employeeID;
float salary;
Employee(int employeeID_, float salary_) {
employeeID = employeeID_;
salary = salary_;
}
}
How could I sort this array based on salary (...and then ideally put the results in a new array)?
Based on web research so far, I am seeing some information about using Comparators in Java, but I'm wondering how I would embed a Comparator in Processing so it worked properly.
(I have experience coding Processing, but not Java.)
Thanks for any assistance anyone can provide!
I would like to select the "top 20" objects, based on a specific variable.
I think this is really a version of the question: "How can I sort an object array based on a specific object variable?"
So I think that I can provide a simplified example of my question. Assume the following code:
Employee[] employees;
void setup() {
employees = new Employee[3];
employees[0] = new Employee(0,20000.00);
employees[1] = new Employee(1,40000.00);
employees[2] = new Employee(2,30000.00);
}
class Employee {
String firstName;
String lastName;
int employeeID;
float salary;
Employee(int employeeID_, float salary_) {
employeeID = employeeID_;
salary = salary_;
}
}
How could I sort this array based on salary (...and then ideally put the results in a new array)?
Based on web research so far, I am seeing some information about using Comparators in Java, but I'm wondering how I would embed a Comparator in Processing so it worked properly.
(I have experience coding Processing, but not Java.)
Thanks for any assistance anyone can provide!
1