Ambu Ambu - 5 months ago 9
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>();


label1
contains names (like "John" or "car") and
label2
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
label2
, but I have no idea how to sort
label1
in exaclty the same way (using
label2
objects). Here is my
Comparator
class:

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

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){
       this.name = 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.

Comments