Sort ArrayList of Array in Java

后端 未结 7 1088
感动是毒
感动是毒 2020-11-29 09:20

What is the best way to sort an ArrayList in Java?

Where String[] is...

String[] = new String[] { \"abc\", \"abc\", \"ab         


        
7条回答
  •  半阙折子戏
    2020-11-29 10:20

    Start with Collections.sort, the one that takes a custom Comparator. You'll need to write a custom Comparator for this also.

    For instance, assuming you want to rely on the natural ordering of Strings as defined in their compareTo method:

    public static void main(String[] args) throws Exception {
            ArrayList listOfStringArrays = new ArrayList();
            listOfStringArrays.add(new String[] {"x","y","z"});
            listOfStringArrays.add(new String[] {"a","b","c"});
            listOfStringArrays.add(new String[] {"m","n","o"});
            Collections.sort(listOfStringArrays,new Comparator() {
                public int compare(String[] strings, String[] otherStrings) {
                    return strings[1].compareTo(otherStrings[1]);
                }
            });
            for (String[] sa : listOfStringArrays) {
                System.out.println(Arrays.toString(sa));
            }
            /* prints out 
              [a, b, c]
              [m, n, o]
              [x, y, z]
            */ 
    
        }
    

提交回复
热议问题