Since Date implements Comparable, it has a compareTo method just like String does.
So your custom Comparator could look like this:
public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}
The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.
Your sorting code would be just about like you wrote:
Collections.sort(Database.arrayList, new CustomComparator());
A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:
Collections.sort(Database.arrayList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
Since java-8
You can now write the last example in a shorter form by using a lambda expression for the Comparator:
Collections.sort(Database.arrayList,
(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
And List has a sort(Comparator) method, so you can shorten this even further:
Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:
Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
All of these are equivalent forms.
Answer from Michael Myers on Stack OverflowSince Date implements Comparable, it has a compareTo method just like String does.
So your custom Comparator could look like this:
public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}
The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.
Your sorting code would be just about like you wrote:
Collections.sort(Database.arrayList, new CustomComparator());
A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:
Collections.sort(Database.arrayList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
Since java-8
You can now write the last example in a shorter form by using a lambda expression for the Comparator:
Collections.sort(Database.arrayList,
(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
And List has a sort(Comparator) method, so you can shorten this even further:
Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:
Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
All of these are equivalent forms.
Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).
Two examples:
public class Number implements Comparable<Number> {
private int value;
public Number(int value) { this.value = value; }
public int compareTo(Number anotherInstance) {
return this.value - anotherInstance.value;
}
}
public class Chair {
private int weight;
private int height;
public Chair(int weight, int height) {
this.weight = weight;
this.height = height;
}
/* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
public int compare(Chair chair1, Chair chair2) {
return chair1.getWeight() - chair2.getWeight();
}
}
class ChairHeightComparator implements Comparator<Chair> {
public int compare(Chair chair1, Chair chair2) {
return chair1.getHeight() - chair2.getHeight();
}
}
Usage:
List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);
List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());
// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
public int compare(Chair chair1, Chair chair2) {
...
}
});
[Java] How to sort an arraylist of Objects, based on Objects String field?
java - How to sort Objects in an Arraylist with an Object parameter - Stack Overflow
Sorting an ArrayList of objects by their attribute of type double in Java/OOP
Sort Java ArrayList based on an object's attribute
How do i alphabetically sort an arraylist of objects, based on the objects field "name". I have object Car, with a compareTo method:
@Override
public int compareTo(Car cName) {
int last = this.carName.compareTo(cName.carName);
return last == 0 ? this.carName.compareTo(cName.carName) : last;
}In a separate class there is an array list that captures all of these Car Objects. I need to sort that list alphabetically, then print out the table of Car Objects in alphabetical order. Im stuck trying to implement the above into the sort for the arraylist that i will iteratively print over.
I have looked at Collections.sort() but i don't want to edit the class name to implement comparator.
public void printRacers() {
// get
//
ArrayList<Car> carNames = new ArrayList<>();
carNames.addAll(racers);
System.out.println("Car name Race Car number");
for (int i = 0; i < carNames.size(); i++) {
Car c = carNames.get(i);
String cName = c.getCarName();
String cRace = d.getRaceName();
int sNum = c.getCarNumber();
String outputString = cName + " " + cClass + " " + sNum;
System.out.println(outputString);
}Im really stuck on this and would appreciate anyone's help!
Thanks
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());
}
});
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.
How's it going everyone?
I need some help in this. So I have this method below that works fine and basically prints the toString representation of different employees by going through each one in the Arraylist of employees objects called Company. Employees are objects with the following attributes: ID, name and gross salary. Now I have to create another method that does the same thing pretty much, but this time prints the toString of my employees by ascending order sorted by the gross salary of employees which is a method I have called getEmployeeGrossSalary() because i'm using encapsulation. I tried to use Arrays.sort for the first time but I'm not really getting anywhere. Anyone could give some hints or has a simple plan for me to implement this?
N.B: My method to create has to return a String which is the toStrings of the employees in my Company ArrayList otherwise I would have problems in the testings my professor made.
Always appreciative of your help <3
//From my company class
public String printAllEmployees(){
StringBuilder printEmployees = new StringBuilder();
for (Employee employee : Company){
printEmployees.append(employee.toString()).append("\n");
} return "All registered employees: \n" + printEmployees;
}//From my employee class
public String toString() {
String grossSalaryTruncated =
String.format("%.2f",this.getEmployeeGrossSalary());
return this.getEmployeeName() + "'s gross salary is " + grossSalaryTruncated + " USD per month.";
}Ended up with this (below) and it worked somehow xD. Can someone just explain how it is working? I'm not really familiar with the syntax..
public String printSortedEmployees() {
StringBuilder printSortedEmps = new StringBuilder();
Company.sort(Comparator.comparingDouble(Employee::getEmployeeGrossSalary));
for (Employee employee : Company) {
printSortedEmps.append(employee.toString()).append("\n");
}
return "Employees sorted by gross salary (ascending order): \n" + printSortedEmps;
}I'm trying to sort an ArrayList in alphabetical order, based on an attribute of the objects the ArrayList contains. For example: I have an object that represents a product and I want to sort the products based on the suppliers name of the attribute. This attribute is a string and could be something like "Old Navy", "Gap", "Peebles", etc.
Is it possible to do a lambda and sort based on product.supplierName? I was thinking of just putting everything into a HashMap with the key being the suppliers name, and then looping over the keys and appending each keys value to an ArrayList, but this doesn't seem like the most efficient method.