I have an unsorted list but I want to sort in a custom way i.e.
item_one_primary.pls
item_one_secondary.pls
item_one_last.pls
item_two_last.pls
item_two_primary.pls
item_two_secondary.pls
item_three_secondary.pls
item_three_last.pls
item_three_primary.pls
Here is my predefined order : primary, secondary, last
Above unordered list once the ordering is applied should look like this :
item_one_primary.pls
item_one_secondary.pls
item_one_last.pls
item_two_primary.pls
item_two_secondary.pls
item_two_last.pls
item_three_primary.pls
item_three_secondary.pls
item_three_last.pls
I tried something with comparator but I end up something like this :
item_one_primary.pls
item_two_primary.pls
item_three_primary.pls
...
Does anyone have an idea how to get this sorted?
Here is some code I've used :
List<String> predefinedOrder;
public MyComparator(String[] predefinedOrder) {
this.predefinedOrder = Arrays.asList(predefinedOrder);
}
@Override
public int compare(String item1, String item2) {
return predefinedOrder.indexOf(item1) - predefinedOrder.indexOf(item2);
}
I didn't include the splits(first split by dot(.) second split by underscore(_) to get the item in pre-ordered list).
Yes, ArrayList is an ordered collection and it maintains the insertion order.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.
Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.
You have to use a Comparator
that checks first the item number and only if they are equal, check your predefined order.
Try something like this:
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
String[] a1 = s1.split("_");
String[] a2 = s2.split("_");
/* If the primary elements of order are equal the result is
the order of the second elements of order */
if (a1[1].compareTo(a2[1]) == 0) {
return a1[2].compareTo(a2[2]);
/* If they are not equal, we just order by the primary elements */
} else {
return a1[1].compareTo(a2[1]);
}
}
This is just a basic example, some extra error checking would be nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With