简体   繁体   English

在 Java 中对数组的 ArrayList 进行排序

[英]Sort ArrayList of Array in Java

What is the best way to sort an ArrayList<String[]> in Java?在 Java 中对ArrayList<String[]>进行排序的最佳方法是什么?

Where String[] is... String[]在哪里...

String[] strAarray = new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" };

Now I want to sort the whole ArrayList by the 2nd value of String[] (at index 1).现在我想通过String[]的第二个值(在索引 1 处)对整个 ArrayList 进行排序。 I need to loop through each and every String[] and then its child at index 1.我需要遍历每个String[]然后它的子节点在索引 1 处。

Any ideas?有什么想法吗?

Edit:编辑:


I have more descriptions.我有更多的描述。 I am actually getting schools from some XML file and every node in XML has 7 attributes.我实际上是从一些 XML 文件中获取学校的,XML 中的每个节点都有 7 个属性。 Now I am creating an ArrayList of String[] which is holding those school nodes from XML and String[] strArray itself is holding attributes of particular node.现在我正在创建一个String[] ArrayList,它保存 XML 中的那些学校节点,而String[] strArray本身保存特定节点的属性。

Now, the way I want to sort it is, it should sort according to State of school which is the 2nd attribute in XML and index 1 in String[] inside ArrayList.现在,我想对它进行排序的方式是,它应该根据学校状态进行排序,这是 XML 中的第二个属性和 ArrayList 中String[]索引 1。

I need to loop through each and every School first (node in XML, String[] in Java) and then I will have to filter State (State attribute in XML, String[1] in Java).我需要首先遍历每个学校(XML 中的节点,Java 中的String[] ),然后我必须过滤 State(XML 中的 State 属性,Java 中的String[1] )。

Start with Collections.sort, the one that takes a custom Comparator .Collections.sort开始, 它采用自定义 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:例如,假设您想依赖在 compareTo 方法中定义的字符串的自然顺序:

public static void main(String[] args) throws Exception {
        ArrayList<String[]> listOfStringArrays = new ArrayList<String[]>();
        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<String[]>() {
            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]
        */ 

    }

You create a Comparator<String[]> like so:你创建一个Comparator<String[]>像这样:

new Comparator<String[]>() {
  public int compare(String[] first, String[] second) {
    return first[1].compareTo(second[1]);
  }
}

then pass it to Collections.sort() .然后将其传递给Collections.sort()

You might want to do some checking if the second element is actually present in the array.您可能想要检查数组中是否确实存在第二个元素。 You could also do a custom comparison if the standard String comparison isn't enough.如果标准字符串比较不够,您还可以进行自定义比较。

您编写了一个Comparator来比较正确的孩子的两个String[] ,然后将其传递给Collections.sort(List<T> list, Comparator<? super T> c)

This is extremely easy to do with Java 8. Just write:这在 Java 8 中非常容易实现。只需编写:

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

For example, the following code:例如,以下代码:

List<String[]> 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]

Based on your edit: Your String[] should be a School object to contain your attributes.根据您的编辑:您的 String[] 应该是一个 School 对象来包含您的属性。 Make your School object implement Comparable and that will allow easy sorting with Collections.sort().使您的 School 对象实现 Comparable,这将允许使用 Collections.sort() 轻松排序。

Suppose we have a list of arrays [["x", "y","z"], ["a", "b", "c"], ["m", "n", "o"]]假设我们有一个数组列表[["x", "y","z"], ["a", "b", "c"], ["m", "n", "o"]]

We can use list.sort() instead of Collections.sort().我们可以使用 list.sort() 而不是 Collections.sort()。

To sort, we can adopt a cleaner way using lambdas and method references.为了排序,我们可以采用更简洁的方式使用 lambda 和方法引用。

Using lambda:使用拉姆达:

listOfStrings.sort((a, b)->a[1].compareTo(b[1]));

Using method reference:使用方法参考:

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

Outputs:输出:

[a, b, c]
[m, n, o]
[x, y, z]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM