Question

I need to sort the ArrayList with respect to column.That is In My ArrayList,each row contains some float values and a string.Each of them is separated using commas.

Example:

1 row:---  4.9,5.1,2.3,1.0,classA

likewise ALL ROWS.

So I want to sort this arraylist based on each values(based on the 1st val of all rows,similarly all rows).

Here How I use Comparator and Comparable?

Was it helpful?

Solution 2

You need to use Collections#sort. It will take your Array List and a Comparator.

You can create anonymous Comparator and in its compareTo method you will obtain that first value by splitting both the string and than compare them and return -1,0,1 accordingly.

Hope this helps.

OTHER TIPS

public class FieldComparator implements Comparator<String> {

    private int column;
    private int numberOfFloats;

    public FieldComparator(int column, int numberOfFloats) {
        this.column = column;
        this.numberOfFloats = numberOfFloats;
    }

    @Override
    public int compare(String o1, String o2) {
        String[] o1Fields = o1.split(",");
        String[] o2Fields = o2.split(",");
        if (column < numberOfFloats) {
            return new Float(o1Fields[column]).compareTo(new Float(o2Fields[column]));
        } else {
            return o1Fields[column].compareTo(o2Fields[column]);
        }
    }   
}

You can use instance of this class as Comparator while sorting or anything else. Refer to documentation of Comparator and Collections for sorting.

Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top