开发者

Sorting ArrayList of String[]

开发者 https://www.devze.com 2023-01-05 10:38 出处:网络
I have an arraylist of String[]: ArrayList< String [] > mystuff = 开发者_如何学Pythonnew ArrayList < String [] > ();

I have an arraylist of String[]:

ArrayList< String [] > mystuff = 开发者_如何学Pythonnew 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


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));
        }
    }   
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号