Sorting ArrayList

Hi,

I can’t find how to sort an ArrayList by one of the variables of the contained objects.

Let’s say I have a class like this one:

class Event {
  int position;
  int value;

  Event(int p, int v) {
    position = p;
    value = v;
  }
}

I want to sort my ArrayList of events by the events’ position or value. Isn’t there a way to do that other than creating the sorting algorithm myself?

Thanks in advance for your help.

1 Like
2 Likes

Thank you. Unfortunately I don’t understand anything from those links :frowning: I guess it’s less work to learn how to create a basic sorting algorithm than learning how to understand those code examples you posted… I just hoped there was an easy way. I guess it’s useful homework anyway.

I guess this is a nice place to start, in case anyone is having the same question…

1 Like

Hi Yann,

You can make your class implements the Comparable interface.

Then you need to override the compareTo(Object o) function. It return an int that is negative if the current object is smaller than the one you pass by argument, 0 if they are the same and bigger if positive.

Then you simply need a call to the Collection.sort() function.

Here is an example:

import java.util.Collections;

void setup() {
  ArrayList<Event> events = new ArrayList<Event>();

  for (int i = 0; i < 10; i++) {
    events.add(new Event((int)random(100)));
  }
  
  println("Before sorting:");
  for (Event e : events) {
    println(e.value);
  }

  Collections.sort(events);
  
  println("");
  println("After sorting:");
  for (Event e : events) {
    println(e.value);
  }
}

class Event implements Comparable<Event> {
  public int value;

  Event(int value) {
    this.value = value;
  }

  @Override
    int compareTo(Event other) {
      return this.value - other.value;
    }
}

3 Likes

Thanks jb4x,

I could use the algo from the Coding Train tutorial. I tried your method as well, both worked, learnt 2 ways of sorting an array, happy :smiley: Java is a lot more complex than Processing suggests, it’s kind of scary but good to know in the same time!

1 Like