Collections.sort(testList);
Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Here is the documentation for Collections.
How can I sort an arrayList containing objects without using a sort method from the java collections library?
Sorting an ArrayList of objects by their attribute of type double in Java/OOP
Collections.sort(testList);
Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Here is the documentation for Collections.
Descending:
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});
I have this code I am working on for a homework assignment, but the professor has specified that we cannot use anything from java collections. The issue is that all of his examples use collections, and all of his examples about sorting only cover sorting an int array. The code I am writing has to sort the array by both "rollno"(the int variable assigned to each "student" object) and by "name"(the string variable assigned to each "student").
The assignment calls for the use of a selection sort method, so I want to sort the numbers in order from 1-10 and sort the names by string length. If anyone can guide me forward on this I would greatly appreciate it because I am lost on how to even begin a selection sort method.
Sidenote: The github has four files in it; "arrSort", "Student", "rollComp", and "nameComp". "arrSort" is the main method and is where I am trying to implement the sort method, "Student" is the object class, "rollComp" and "nameComp" are both comparator classes. All of these files are copied directly from my IDE, and if you notice ANY errors in how I have formatted anything, or if you have any other questions please let me know.
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.
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) {
...
}
});
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;
}