(48) 3332-8540

Ordering List of Objects in Java

Whoever in their life as a programmer, whether starting with the C programming language or directly with Java, has not faced some problems with Segmentation fault and NullPointException when working with vectors, mainly due to accessing indexes that did not exist. In the C programming language there is not much escape for these cases, besides implementing all the logic for manipulating these vectors. One of the classic exercises in C is to sort a vector in ascending or descending order, using some logic with fors and ifs.

When starting to study Java, we also learned to use vectors first and faced the same problems as in C, we even did the same exercises already done in C about vectors. But then we thought, Java being a higher level language than C, isn't there a more elegant solution? The answer comes from the Collections Framework, which is a robust API created by Sun that has several classes that represent advanced data structures, such as ArrayList and LinkedList, and useful functions for working with vectors.

The objective of this article is not to give a complete explanation of how to use the Collections API syntax, with the first two paragraphs being a brief introduction to the subject, but rather how to sort a list of objects in Java without having to implement any fancy logic. A list of objects in Java can be easily sorted using the sort method of the Collections API. As an example we will create a list of strings and add some words to it, then we will print this list to see its order. Then we will run the sort method to sort the list and print the list again to compare the result.

[sourcecode language=”java”]
List list = new ArrayList ();

list.add(“fire”);
list.add(“water”);
list.add(“wind”);
list.add(“land”);

for(String i : list){
System.out.println(i);
}

Collections.sort(list);
System.out.println(“Ordering the list:”);

for(String i : list){
System.out.println(i);
}
[/sourcecode]

Result:

[sourcecode language=”powershell”]
fire
water
wind
Earth
Ordering the list:
water
fire
Earth
wind
[/sourcecode]

As can be seen above, the list has been reordered in ascending order. But how did the sort method know how to organize the list? It needs to use an int compareTo(Object) method to be able to sort the list, which returns zero if the compared object is equal to this object, a negative number if this object is smaller than the given object, and a positive number if this object object is greater than the given object. This method is defined in the Comparable interface, which must be implemented by the class that will be sorted in a list. It is not necessarily mandatory for the class to implement the Comparable interface. When calling the sort method, a method that will do the sorting can also be passed as a parameter in addition to the list that will be sorted.

We understand how sorting is done, but we still haven't implemented the Comparable interface and no logic for sorting. How can the list be sorted with the sort method? The answer is that the string class already implements the Comparable interface that orders its elements alphabetically. Other classes in Java that implement this interface are: BigDecimal, BigInteger, Byte, ByteBuffer, Character, CharBuffer, Charset, CollationKey, Date, Double, DoubleBuffer, File, Float, FloatBuffer, IntBuffer, Integer, Long, LongBuffer, ObjectStreamField, Short, ShortBuffer and URI that can be sorted simply using the sort method.

Now we come to the case if we want to order a list of objects of a class that we create ourselves. To do this, our class must implement the Comparable interface. We will use as an example the class below called car, which contains only two attributes, engine capacity and color, and a constructor that receives these attributes.

[sourcecode language=”java”]
public class Car {

private String color;
private int displacement;

public Car(String color, int engine capacity) {
super();
this.color = color;
this.displacement = displacement;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public int getCilindrada() {
return cylinder capacity;
}

public void setCylinder(int cylinder) {
this.displacement = displacement;
}
}
[/sourcecode]

We will now make the necessary modifications to our car class so that we can sort a list in our class using the sort method. Firstly, our class must implement the Comparable interface and consequently implement the sort method, remembering that this method returns zero if the object is equal, a negative number if it is smaller and a positive number if it is larger. We will also decide how we want our list of cars to be sorted, the sorting will be done in descending order of engine capacity, and if there is the same, it will be sorted in alphabetical order by color. The finished class can be seen below.

[sourcecode language=”java”]
public class Car implements Comparable {

private String color;
private int displacement;

public Car(String color, int engine capacity) {
super();
this.color = color;
this.displacement = displacement;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public int getCilindrada() {
return cylinder capacity;
}

public void setCylinder(int cylinder) {
this.displacement = displacement;
}

public int compareTo(Car car) {
if(this.cylinder > car.cylinder){
return -1;
}
else if(this.cylinder < car.cylinder){
return 1;
}
return this.getCor().compareToIgnoreCase(car.getCor());
}
}
[/sourcecode]

To show that the ordering really worked, we will do a test, where we will create a list of cars, add some cars to the list, some with the same engine capacity and different colors. Then we will print this list of cars, run the sort method and display the list again to see if the sorting actually occurred.

[sourcecode language=”java”]
List cars = new ArrayList ();

cars.add(new Car(“Blue”,500));
cars.add(new Car(“Green”,300));
cars.add(new Car(“Orange”,700));
cars.add(new Car(“Brown”,300));
cars.add(new Car(“Yellow”,700));

for(Car c : cars){
System.out.println(“Car color “+c.getColor()+” and “+c.getCilindrada()+” cylinders.”);
}

Collections.sort(cars);
System.out.println(“Ordering the list:”);

for(Car c : cars){
System.out.println(“Car color “+c.getColor()+” and “+c.getCilindrada()+” cylinders.”);
}
[/sourcecode]

Result:

[sourcecode language=”powershell”]
Blue car with 500 cc.
Green car with 300 cylinder capacity.
Orange car with 700 cc.
Brown car with 300 cc.
Yellow car with 700 cc.
Ordering the list:
Yellow car with 700 cc.
Orange car with 700 cc.
Blue car with 500 cc.
Brown car with 300 cc.
Green car with 300 cylinder capacity.
[/sourcecode]

As expected the sorting worked correctly. That's what this article proposes to address, it may be something simple for some people, but for those who don't know it, it can be of great help, making your work much easier.

Doubts? Suggestions? Leave your comment!

en_USEN