Ambu Ambu - 1 year ago 113
Java Question

How to sort ArrayList according to another ArrayList?

I've got 2 ArrayList:

ArrayList<JLabel> label1 = new ArrayList<JLabel>();
ArrayList<JLabel> label2 = new ArrayList<JLabel>();

contains names (like "John" or "car") and
contain ratings (like "8.5" or "10.0"). I wanna sort both lists by rating.

I've used
Collections.sort(label2, new Sort());
to sort
, but I have no idea how to sort
in exaclty the same way (using
objects). Here is my

class Sort implements Comparator<JLabel>{
public int compare(JLabel o1, JLabel o2) {
Double a = Double.parseDouble(o1.getText());
Double b = Double.parseDouble(o2.getText());
return b.compareTo(a);

Any ideas? :C

Answer Source

Given that you have no relationship defined between the two lists I think you should consider wrapping the two values up in a class:

class Foo {

   private String name;
   private double rating;

   public Foo(String name, double rating){ = name;
       this.rating = rating;

   // getters & setters

You can then have List<Foo> and sort the list based on the value of rating.

In Java 8 this would be as simple as calling the sort() method, which is now provided in List, with a lambda expression passed in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download