简体   繁体   中英

Sort on first entry of ArrayList in ArrayList

I have an ArrayList that consists of an ArrayList that constists of Strings: ArrayList<ArrayList<String>> . How can I sort on the first entry of he inner ArrayList? For example I would like this:

a = [['1','apple'],['3','pear'],['2','banana'],['1',orange']]

to become:

a_sorted = [['1','apple'],['1','orange'],['2','banana'],['3','pear']]

The order of duplicate first entries (like apple and orange ) do not matter. I've tried using Collections.sort(a,new ColumnComparator()) but it will not accept ArrayLists. This is the class I used:

public class ColumnComparator implements Comparator<ArrayList<String>>{
    public int compare(ArrayList<String> ar1, ArrayList<String> ar2){
        return ar1.get(0).compareTo(ar2.get(0));
    }
}

You can create a Map <String, ArrayList<String>> with first entry of the ArrayLists as key and the ArrayList itself as value. Then sort the Map (use Sorted Map or a Comparator to sort on the Map keys) on keys and you will get what you want.

Instead of storing an Array of an Array, why don't you create a custom Class that implements Comparable . eg.

class Fruit implements Comparable<Fruit> {
protected int number;
protected String name;

public Fruits(int number, String name) {
    this.number = number;
    this.name = name;
}

@Override
public int compareTo(Fruit f) {
    return number < f.number;
    // or depending on if ascending or descending order wanted
    // return number > f.number 
}
}

Then to sort just run Collections.sort(a) . This way is flexible and easily extended.

Why cant you use a this ArrayList<Map<String,String>> instead of ArrayList<ArrayList<String>> . You can easily sort the Map on the key by using TreeMap. Note: This will only work if you have only two entries in your inner arraylist.

If you really want to do it that way, you can try this:

import java.util.Comparator;

public class ColumnComparable implements Comparator<ArrayList<String>>{

    @Override
    public int compare(ArrayList<String> o1, ArrayList<String> o2) {
        return (Integer.parseInt(o1.get(0)) > Integer.parseInt(o2.get(0)) ? -1 : (Integer.parseInt(o1.get(0)) == Integer.parseInt(o2.get(0)) ? 0 : 1));
    }
}

The code was found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM