Question

Is there any equalent for PHP's usort function in Java? Some library or anything. Thanks.

I guess it could be programmable through some iterfaces, so if you know about something i'd be glad.

Was it helpful?

Solution

You can use java.util.Arrays.sort(T[] a, Comparator<? super T> c). You'd have to implement the Comparator, which would be equivalent to implementing the function you pass to PHP's usort.

A silly example of an implementation of the comparator (for Strings):

public class MySillyExampleClass implements Comparator<String> {
    public int compare(String s1, String s2) {      
        return s1.length()-s2.length();
    }
}

OTHER TIPS

You can use either Arrays.sort or Collections.sort. You only need to implement your own Comparator

AFAIK There isn't such a tool.

What you can do is sort an List of elements with Collection.sort() and a custom Comparator.

What I would do is transform the values so that a natrual sort is correct. After the sort transform the values back. If you have to you can use a larger type e.g. int[] => long[] where the top bits have the transformed sortable value and the lower bits have the original => int[] by taking the lower bits.

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