Sort ArrayList of Array in Java

后端 未结 7 1085
感动是毒
感动是毒 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:04

    This is extremely easy to do with Java 8. Just write:

    list.sort(Comparator.comparing(a -> a[1]));
    

    For example, the following code:

    List list = Arrays.asList(
        new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" },
        new String[] { "xyz", "xyz", "xyz", "xyz", "xyz", "xyz", "xyz" },
        new String[] { "fgh", "fgh", "fgh", "fgh", "fgh", "fgh", "fgh" });
    
    list.sort(Comparator.comparing(a -> a[1]));
    list.stream().map(Arrays::toString).forEach(System.out::println);
    

    Will yield the wanted result:

    [abc, abc, abc, abc, abc, abc, abc]
    [fgh, fgh, fgh, fgh, fgh, fgh, fgh]
    [xyz, xyz, xyz, xyz, xyz, xyz, xyz]
    

提交回复
热议问题