-1

I have an array with the following syntax:

ArrayList<String[]> outerArr = new ArrayList<String[]>();
String[] str = {art1, art2, String.valueOf(sim)};
outerArr.add(str);

After certain loops and changes, I get something like:

name1 name2 0.11
name1 name3 0.14
name2 name4 0.12

I need to sort them by the third column. How is it possible to implement?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Cap
  • 353
  • 2
  • 16

2 Answers2

1

Be forewarned that this will compare lexicographically - that is, if you have numbers 1.0, 2.0, 10.0,11.0, and 20.0, the order will be 1.0, 10.0, 11.0, 2.0, and 20.0.

This is a very rudimentary approach in Java 8 using a simple Comparator. Be cautioned that this won't check for null on either side.

Comparator<String[]> stringArrayComparator = (left, right) ->
                         left[2].compareTo(right[2]);

You could then use this in Collections.sort.

Collections.sort(outerArr, stringArrayComparator);
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

You could use the Column Comparator which is a general purpose Comparator that allows you to specify the column you want to sort on.

The ColumnComparator will work on data stored in a Array or a List.

If you don't want to use that class, the blog also shows how to create a simple Comparator for a given column in theArray`.

camickr
  • 321,443
  • 19
  • 166
  • 288