Hi,
I'm trying to find a way to sort an ArrayList by absolute value, similar to:
my @sortedArray= sort { abs $a <=> abs $b } @unsortedArray
in Perl
So, given an ArrayList of Integers: -7 -12 -3 5 8 9,
I want to sort them to be in the order of absolute value, namely -3 5 -7 8 9 -12
I've tried the following
public class Compare
{
public ArrayList sortArray(ArrayList valuesToSort )
{
Collections.sort( valuesToSort, getComparator( ) ) ;
return valuesToSort;
}
public static Comparator getComparator( )
{
return new Comparator( )
{
public int compare(Object o1, Object o2 )
{
return Math.abs((Integer)o1).compareTo(Math.abs((Integer)o2));
}
} ;
}
}
and then use it in some other code with
Collections.sort (valuesToSort, getComparator ( ));
But it's not possible to use Math.abs on an Integer, and when I turn the o1 and o2 into ints, the error that I get is that I can't dereference int.
So, firstly, is there a short-cut to doing this, and secondly if there isn't, is there a good way of going about it
Many thanks,
Graham