Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an object ArrayList by an attribute value in Java

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.

like image 220
user2414341 Avatar asked May 25 '13 16:05

user2414341


People also ask

Can you sort an ArrayList of objects in Java?

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.

How do you sort a specific element in an ArrayList?

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.

How do you sort a list of objects based on an attribute of the objects in Java 8?

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.

How do you sort an array of objects by property?

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.


2 Answers

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.

like image 91
arshajii Avatar answered Nov 10 '22 00:11

arshajii


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

like image 34
patz Avatar answered Nov 09 '22 23:11

patz