Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Answer from Mark Elliot on Stack OverflowUse a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
then just use
Collections.sort(nodeList);
[Java] How to sort an arraylist of Objects, based on Objects String field?
java - How to sort List by field in descending order? - 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
If I understood correctly you need refence to method getStatus() its natural order sort
ar.sort(Comparator.comparing(Student::getStatus));
if need reverse order
ar.sort(Comparator.comparing(Student::getStatus).reversed());
The string "Y" comes lexicographically after "N", so you need to reverse the default ordering.
There are some ways to do it, one is negating the result of the comparison function:
Collections.sort(ar, (a, b) - > -a.getStatus().compareTo(b.getStatus());
Another is changing the order of the operands:
Collections.sort(ar, (a, b) - > b.getStatus().compareTo(a.getStatus());