Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an ArrayList<List> in Java [duplicate]

Tags:

java

arraylist

I have an ArrayList<List> where the Lists have string values that hold a name and then a double converted to a string.

Example:

List<String> list = New List; 
list.add("Abraham");
list.add(String.valueOf(0.65));

List<String> list2 = New List; 
list2.add("Bowers");
list2.add(String.valueOf(0.89));

ArrayList<List> arrayList = new ArrayList<>();
arrayList.add(list); 
arrayList.add(list2); 

How can I sort the ArrayList in descending order by the value of the double?

like image 915
Duff Avatar asked May 14 '26 08:05

Duff


2 Answers

Use Collections.sort(arrayList, instanceOfYourOwnImplemenationOfComparator) after having a custom implementation of Comparator<ArrayList>.

Or better, Java is an Object oriented language so create a class dedicated to the storage of your String+double and make it comparable.

class MyClass implements Comparable<MyClass> {
   private String word;
   private double score;

   MyClass(String word, double score) {
       this.word = word;
       this.score = score;
   }

   @Override
   public int compareTo(MyClass o) {
      return (int) Math.round(Math.signum(score - o.score));
   }

}
like image 127
YMomb Avatar answered May 15 '26 22:05

YMomb


I would change your implementation and create a class containing two fields, a String and a Double one. This class would implement the Comparable interface and its compareTo would be based on the double alone. Something like

public class MyClass implements Comparable<MyClass> {
    private double value;
    private String name;

    /*Constructors, setters and getters*/

    public int compareTo(MyClass o) {
        return(new Double(value)).compareTo(myO.getValue));        
    }
}

Then, your code would become:

ArrayList<List> arrayList = new ArrayList<>();
arrayList.add(new MyClass("abraham",0.65)); 
arrayList.add(new MyClass("bowers", 0.89)); 

Collections.sort(arrayList);

I just typed the code, but I believe the idea is pretty straightforward.

I hope it helps.

like image 43
rlinden Avatar answered May 15 '26 23:05

rlinden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!