Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an arraylist of objects java?

So I want an arraylist of objects in java.

I have object1.number and object2.number, object3.number, etc... but those objects have other properties besides number, such as name, distance, etc...

So if it was sorting a string in a array it would just be, put a string in a temporal and let the other string take its place... but in an araryList of objects, how can I do it?

Can I just move objects to that position of the array?

Thanks.

like image 824
user1253201 Avatar asked Apr 13 '12 17:04

user1253201


People also ask

How do you sort an ArrayList of objects in Java 8?

– Use Collections. sort() method for sorting the ArrayList in-place, or Java 8 Stream. sorted() to return a new sorted ArrayList of Objects (the original List will not be modified). – For Descending order, just pass Collections.

How do you sort elements in an ArrayList?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

How do you sort a collection of objects?

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

How do you sort objects in Java?

To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again. The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.


2 Answers

Implement your own comparer:

Arrays.sort(yourArray, new Comparator<YourClass>() {
        @Override
        public int compare(YourClass o1, YourClass o2) {
            //compare object properties
        }
});
like image 123
juergen d Avatar answered Sep 22 '22 15:09

juergen d


You need to implement the comparable interface

implements Comparable

the method that does the work is

public int compareTo(Object obj)
{
}

Please note that object is often replaced by a full on type because of generic syntax which can be used in the implements statement (shown below).

A full example is here in the tutorial docs hope this helps

A full example (take from the above link is as follows), I have added this just in case the link goes dead at some point

import java.util.*;

public class Name implements Comparable<Name> {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (o == null || !(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
    return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}

The client code from the article is:

import java.util.*;

public class NameSort {
    public static void main(String[] args) {
        Name nameArray[] = {
            new Name("John", "Smith"),
            new Name("Karl", "Ng"),
            new Name("Jeff", "Smith"),
            new Name("Tom", "Rich")
        };

        List<Name> names = Arrays.asList(nameArray);
        Collections.sort(names);
        System.out.println(names);
    }
}
like image 31
krystan honour Avatar answered Sep 22 '22 15:09

krystan honour