views:

100

answers:

1

I have an arraylist of String[]:

ArrayList< String [] > mystuff = new ArrayList < String [] > ();

I want to sort them in largest-array-size ascending order. Example:

mystuff = {["this", "is", "item", "one"], ["this", "is", "item", "two"], ["item"], ["item", "three"]}

Should become:

mystuff = {["item"], ["item", "three"], ["this", "is", "item", "one"], ["this", "is", "item", "two"]}

For arrays of equal length, the order doesn't matter.

Edit:

Java compiler version: javac 1.6.0_20

Error that I am facing by using @sepp2k's code: http://pastie.org/private/ienpdtj0ft6czw6nboeva

+7  A: 

Use Collections.sort with a Comparator that compares the length.

Collections.sort(mystuff, new Comparator<String[]>() {
    public int compare(String[] x, String[] y) {
        if(x.length < y.length) {
            return -1;
        } else if(x.length == y.length) {
            return 0;
        } else {
            return 1;
        }
    }
});

Edit: Here's a complete class that compiles and runs without error (and shows the correct result):

import java.util.*;

public class Bla {                         
    public static void main(String[] args) {
        // Create list
        List<String[]> mystuff = new ArrayList<String[]>();
        mystuff.add(new String[] {"lilu", "lolo"});
        mystuff.add(new String[] {"lala"});
        mystuff.add(new String[] {"lila", "blabla", "pfirsichkuchen"});

        // Sort list
        Collections.sort(mystuff, new Comparator<String[]>() {
            public int compare(String[] x, String[] y) {
                if(x.length < y.length) {
                    return -1;
                } else if(x.length == y.length) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });

        // Output list
        for(String[] strs : mystuff) {
            System.out.println(Arrays.toString(strs));
        }
    }   
}
sepp2k
Yikes, my compiler throws a bunch of errors. Is it because I am importing:import java.util.*;
curiousgeorge
@khan0: It's not because you're importing `java.util.*`. That's fine. Please edit your question to show the whole code that causes the error and the error message. And your java version.
sepp2k
Ummm ... (potentially) creating two `Integer` instances so that you can use the `compareTo` method seems a bit wasteful.
Stephen C
@StephenC: Ok, I edited to use an if-statement instead.
sepp2k
Thanks a lot @sepp2k, it works now. @Stephen C, I will take your advice and get started on some reading soon times. Thanks a lot guys!
curiousgeorge
The whole if/else block can be removed and replaced with return x.length-y.length. The value doesn't matter, just whether it's zero, positive or negative.
Noel M