在Java数组排序的ArrayList [英] Sort ArrayList of Array in Java
问题描述
什么是排序的最佳途径的ArrayList<的String []>
在Java中
What is the best way to sort an ArrayList<String[]>
in Java?
其中string [] ...是
Where String[] is...
String[] = new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" };
现在我想通过字符串的第二个值[]整的ArrayList(索引1)排序。我需要遍历每个字符串[],然后它的子索引1。
Now I want to sort the whole ArrayList by 2nd value of String[] (at index 1). I need to loop through each and every String[] and then its child at index 1.
任何想法?
EDITED
我有更多的说明。我其实一些XML文件中获取学校和XML每个节点有7个属性。现在,我创建这是保持从XML和String []数组本身这些学校的节点是抱着特定节点的属性的String []的ArrayList
I have more description. I am actually getting schools from some XML file and every node in XML has 7 attributes. Now I am creating an ArrayList of String[] which is holding those school nodes from XML and String[] array itself is holding attributes of particular node.
现在,我想对它进行排序是这样的,应根据学校的状态,这是的String []内的ArrayList中的XML和索引1第二属性进行排序。
Now, the way I want to sort it is, it should sort according to State of school which is 2nd attribute in XML and index 1 in String[] inside ArrayList.
我需要通过每一个回路学校第一个(在XML节点的String []在Java中),然后我将不得不过滤状态(XML State属性,字符串[1]在Java中)。
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).
是否清楚了吗?
推荐答案
开始以<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\">Collections.sort,一,需要一个自定义的比较。你需要编写一个自定义比较了解本也。
Start with Collections.sort, the one that takes a custom Comparator. You'll need to write a custom Comparator for this also.
例如,假设你想依靠字符串的自然顺序,在他们的compareTo方法定义的:
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<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]
*/
}
这篇关于在Java数组排序的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!