How to Sort an Array of Objects in Java

How to sort an array of objects in Java?

You have two ways to do that, both use the Arrays utility class

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.

Example

class Book implements Comparable<Book> {
public String name, id, author, publisher;
public Book(String name, String id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
public String toString() {
return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
}
@Override
public int compareTo(Book o) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return toString().compareTo(o.toString());
}
}

@Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};

// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));

// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}

Output

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

Sorting array of objects by field

Just for completeness, when using Java 8, you can use Comparator.comparing to create a simple comparator for some attribute, e.g. Comparator.comparing(Person::getAge), or using lambda, like Comparator.comparing(p -> p.age), if there is not getter method for the age.

This makes it particularly easy to chain comparators for different attributes, using thenComparing, e.g. for sorting primarily by age, and then by name in case of ties:

Comparator.comparing(Person::getAge).thenComparing(Person::getName)

Combine that with Arrays.sort, and you are done.

Arrays.sort(arrayOfPersons, Comparator.comparing(Person::getAge));

Sort an array of objects in Java

In your comments below the question you say you have:

Project[] array = new Project[3];

If I were you I'd declare Project as

public class Project implements Comparable<Project> {

@Override
public int compareTo(Project other) {
return this.id - other.id; // or whatever property you want to sort
}

Then you can sort your array by simply calling

Arrays.sort(array);

If you don't want your class to implement the Comparable interface you can pass a comparator to Arrays.sort():

    Arrays.sort(array, new Comparator<Project>() {
@Override
public int compare(Project o1, Project o2) {
return o1.id - o2.id; // or whatever property you want to sort
}
});

I used an anonymous one, you could also extract it to it's own class if needed elsewhere.

How to sort array of objects in Java by alphabet

First, you should have a Book class for individual books. Assuming your Library is a list of books you can then do it like this.

List<Book> sortedLibrary = library.stream()
.sorted(Comparator.comparing(book -> book.author))
.collect(Collectors.toList());

Since no details were provided about the author name field it sorts on the entire field whether its first, last or both names.

If you want to sort them in place, a cleaner approach would be.

library.sort(Comparator.comparing(book->book.author));

How to sort an array of objects w.r.t. key using Java?

Create a class to hold your two related data elements (index and value) as fields (presumably with getters and setters). Write two Comparator classes, one that sorts by index and one that sorts by value. I would probably create factory methods in the class to get these Comparators.

Rather than create an array of String, you would create an array of your new class. Construct your class instances and assign to the array.

Than you can use Arrays.sort on your array with whichever Comparator is appropriate to efficiently sort the array. This also allows you easy access to the individual fields.

Bro - here is some code to get you started...

public class Bro {
private int index;
private int value;
public Bro (int index, int value) {
this.index = index;
this.value = value;
}
public static Comparator<Bro> getIndexComparator() {
return new Comparator<Bro>() {
public int compare(Bro o1, Bro o2) {
return o1.index - o2.index;
}
}
}
}
Bro[] bros = new Bro[5];
bros[0] = new Bro(1, 220);
...
Arrays.sort(bros, Bro.getIndexComparator());

Java provides two similar interfaces: Comparator and Comparable. If a class has a natural sort order, you would implement Comparable. If you need to sort a class in more than one way, you will implement a Comparator for each sort order that you need.

Sort an array of custom objects in descending order on an int property

Use a Comparator and an ArrayList.

In Java 8

Use the new default and static methods on Comparator!

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos,
Comparator.comparingInt(StudentInformation::getBirthYear).reversed());

It's a brave new world! :)

Or—still better than Java 7—use lambdas!

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, (s1, s2) ->
Integer.compare(s2.getBirthYear(), s1.getBirthYear()));

In Java 7

Use anonymous inner classes.

class StudentDateComparator implements Comparator<StudentInformation> {
public int compare(StudentInformation s1, StudentInformation s2) {
return Integer.compare(s2.getBirthYear(), s1.getBirthYear());
}
}

ArrayList<StudentInformation> infos = new ArrayList<StudentInformation>();
// fill array
Collections.sort(infos, new StudentDateComparator());

Explanation

What the Comparator does is allows anything to compare two objects of the given type (in this case, StudentInformation). You could also make StudentInformation implement Comparable<StudentInformation>, but this way is probably better because there is more than one way to compare student informations (by date, as here, but also by first name, last name, number of classes enrolled, etc.).

By swapping the order of s1 and s2 in the comparator, we induce a reverse order. Another way to do this would be to negate the compare call in the normal order, or to use a normal comparator and wrap it in Collections.reverseOrder.


You could also do this with a standard array.

StudentInformation[] infos = new StudentInformation[10];
// fill array
Arrays.sort(infos, new StudentDateComparator());

how do i sort an array of objects via the comparable interface?

A class implementing Comparable means it has a "natural" sort mechanism.

The one you have defined for your Food class is very strange, based on the product of the length of the type and the calories.

What I think you need are some external comparators, each comparing a different aspect of your class.

A public static class CaloriesComparator implements Comparator<Food> can compare only based on the calories (and then it can compare by the food type).

You can then create a TypeComparator implements Comparator<Food> that first compares the type, and only if the types are equal compares the calories.

You can then use it in the Arrays.sort(<array>, <comparator instance>) sort method.

Using Java 8, you can write the comparators even simpler:
Comparator<Food> comparator = Comparator.comparingDouble(Food::getCalories).thenComparing(Food::getType);



Related Topics



Leave a reply



Submit