Visceras
Visceras

Reputation: 101

Sort array based of specific element

So I have a list of objects, specifically a list of vehicles, that contains cars, motos and bicicles. Each one of this objects has different atributes (car and moto have max velocity while bicicle doesn´t for instance.)

Moto Bicicle and Car are subclasses of Vehicle and Vehicle implements the interface Comparable.

They do have on thing in common, the year when they were made and that's how I wanted to sort my array, using that specific attribute. By default java is sorting based on another attribute the objects have in common which is "color".

This is the code used to sort the arrays.(It has to be this one)

public static <T> void sortArray(Comparable<T>[] a) {
        Arrays.sort(a);
}

Is there a way to select the attribute which I would like to use to sort the list? Thanks for the help in advance.

Upvotes: 1

Views: 196

Answers (2)

wero
wero

Reputation: 32980

You can implement an own comparator and pass it to Arrays.sort(array, comparator). Using lambdas or method handles this is easy:

Vehicle[] v = ...
Arrays.sort(v, (v1,v2) -> v1.getYear() - v2.getYear());

or

Arrays.sort(v, Comparator.comparing(Vehicle::getYear));

Based on that you can write a generic function which sorts an array by a specific attribute:

public static <T, U extends Comparable<? super U>> void sortArray(T[] a, 
    Function<? super T, ? extends U> attribute) {
    Arrays.sort(a, Comparator.comparing(attribute));
}   

and use it with

sortArray(v, Vehicle::getYear);

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

By default Arrays.sort sorts according to the Comparable natural ordering of its elements. If you want to change it, use Arrays.sort(T[] a, Comparator<? super T> c) instead, it allows to define your own comparator.

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(T[], java.util.Comparator)

Upvotes: 2

Related Questions