1

I have a ArrayList<String[]>.

example element:

test,400000,30

So the Array list contains this type of String arrays. Lets divide last value by middle value in one array. so it will be like this.

30/400000 = 0.000075

I need to sort the array list by these values (lastvalue/middlevalue) in ascending order.

How can I do that?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
woof
  • 13
  • 2
  • possible duplicate of [Sorting an array of Strings with Java](http://stackoverflow.com/questions/12986386/sorting-an-array-of-strings-with-java) – Justin Skiles Oct 18 '14 at 14:16
  • 1
    @justin Skiles. This is not a duplicate of that question. that question is about string array sorting and my one is about string[] array list sorting. – woof Oct 18 '14 at 14:18

1 Answers1

0

You can write your custom Comparator:

public class StringArrayComparator implements Comparator<String[]> {
    @Override
    public int compare(String[] a, String[] b) {
        double aVal = Double.valueOf (a[2]) / Double.valueOf (a[1]);
        double bVal = Double.valueOf (b[2]) / Double.valueOf (b[1]);

        return Double.compare(aVal, bVal);
    }
}

And then use it with Collections.sort:

List<String[]> myList = /* some value */;
Collections.sort(myList, new StringArrayComparator());

Note:
This implementation assumes valid input - that all the arrays are (at least) three elements long, that the second and third elements are parsable to integers, and that the second element (which we divide by) isn't zero.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • @ mureinik, Integer.compare is has not found error comes. :( – woof Oct 18 '14 at 14:20
  • @GáborBakos yup, you're right - changed to use `Double`s. Thanks for noticing! – Mureinik Oct 18 '14 at 14:22
  • @woof I did not understand your comment - but see my latest edit. As Gabor pointed out, this should be done with `Double`s. – Mureinik Oct 18 '14 at 14:22
  • @ mureinik, Sorry I used wrong grammar. In the return statement java says "cannot resolve method compare(double,double)" – woof Oct 18 '14 at 14:26
  • @woof - missed a spot when I addressed Gabor's comment - it should have been a call to `Double.compare` - fixed now. – Mureinik Oct 18 '14 at 14:27
  • Yes. marked as the correct answer. Thank you so much. What can I change If I need to sort in descending order? – woof Oct 18 '14 at 14:36
  • Just reverse the final comparison (`return Double.compare(aVal, bVal);`) and do `return Double.compare(bVal, aVal);` – Mureinik Oct 18 '14 at 14:39
  • @woof Or actually, even better - use `Collections.sort(myList, Collections.reverseOrder(new StringArrayComparator()));` – Mureinik Oct 18 '14 at 14:41