我是新來積極地寫問題在這裏,雖然我已經使用這個網站一段時間了。使用多個索引排序字符串[]的ArrayList
我想根據數組的前兩個索引按照詞彙順序(=自然順序?!)排序ArrayList。目前我使用下面的代碼:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String[]> workingSet = new ArrayList<>();
workingSet.add(new String[]{"MiningCorp", "2265 Betacity"});
workingSet.add(new String[]{"MiningCorp", "6454 Iotacity"});
workingSet.add(new String[]{"Arbiter", "3812 Gammacity"});
workingSet.add(new String[]{"MiningCorp", "1234 Thetacity"});
workingSet.add(new String[]{"Arbiter", "1812 Deltacity"});
Comparator<String[]> staComp = new Comparator<String[]>() {
@Override
public int compare(String[] first, String[] second) {
String composite1 = first[0] + " " + first[1];
String composite2 = second[0] + " " + second[1];
return composite1.compareTo(composite2);
}
};
Collections.sort(workingSet, staComp);
for(String[] arr : workingSet){
System.out.println(Arrays.toString(arr));
}
}
}
這將產生以下輸出:
[Arbiter, 1812 Deltacity]
[Arbiter, 3812 Gammacity]
[MiningCorp, 1234 Thetacity]
[MiningCorp, 2265 Betacity]
[MiningCorp, 6454 Iotacity]
這正是我想要的。 有沒有更優雅的方式使用預建方法?
如果我想按照詞彙順序排列第一個數組條目,但是在這個組中,我希望單個數組按照逆詞法順序排序? 爲此,是否需要第二個比較器來首先對每個數組的第二個索引的條目進行預先排序?
這裏是我想在這個例子:
[Arbiter, 3812 Gammacity]
[Arbiter, 1812 Deltacity]
[MiningCorp, 6454 Iotacity]
[MiningCorp, 2265 Betacity]
[MiningCorp, 1234 Thetacity]
而lambda表達式不適合我全新的,這使得它更清晰的對我來說,他們在java中是如何工作的。謝謝您的回答。 –