I'm new to actively writing questions here, although I've used this site for some time now.
I want to sort an ArrayList in lexicalic order (= natural order?!) depending on the first two indices of the array. Currently I've used the code below:
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));
}
}
}
This should produce the following output:
[Arbiter, 1812 Deltacity]
[Arbiter, 3812 Gammacity]
[MiningCorp, 1234 Thetacity]
[MiningCorp, 2265 Betacity]
[MiningCorp, 6454 Iotacity]
This exactly what I wanted. Is there a more elegant way using prebuilt methods?
What if I wanted to sort by grouping by the first array entry in lexicalic order, but within this group i want the individual arrays to be sorted by inverse lexicalic order? For this, do I need a second comparator to first pre-sort the entries of the second index of each array?
Here is what i want to get for this example:
[Arbiter, 3812 Gammacity]
[Arbiter, 1812 Deltacity]
[MiningCorp, 6454 Iotacity]
[MiningCorp, 2265 Betacity]
[MiningCorp, 1234 Thetacity]