I have ArrayList zombie
, which is populated with an object called Zombie
. Zombie
has the attributes health
, x
, y
. How would I sort the array in ascending order, using the attribute x
of Zombie
, which is set to initially have random values?
I have already found a possible solution to my problem, but I do not understand the syntax of the answer. Explaining that answer may help, also.
An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.
In order to sort elements in an ArrayList in Java, we use the Collections. sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order. where list is an object on which sorting needs to be performed.
Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.
To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
You want to use Collections.sort
in conjunction with a custom Comparator
.
Collections.sort(list, new Comparator<Zombie>() {
@Override
public int compare(Zombie z1, Zombie z2) {
if (z1.x() > z2.x())
return 1;
if (z1.x() < z2.x())
return -1;
return 0;
}
});
Essentially, a Comparator
is a key that signifies how a list should be ordered via its compare
method. With the Comparator
above, we consider z1
to be greater than z2
if z1
has the higher x
value (and we show this by returning 1
). Based on this, we sort list
.
using JAVA 8 do this:
zombie.sort((Zombie z1, Zombie z2) -> {
if (z1.x() > z2.x())
return 1;
if (z1.x() < z2.x())
return -1;
return 0;
});
List interface now supports the sort method directly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With