Use the overload of Arrays.sort that takes an implementation of Comparator<T> as the second parameter. Implement the Comparator<String> interface to implement custom comparison.
I have used a HashMap to assign a weight/priority to each entry and then used this priority to compare. An object of higher priority will be considered greater. You can customize the priority by changing the second argument of map.put(). The way the compare function of the Comparator<T> interface works is, for every two objects, if:
- if the
int returned is negative, second element is greater
- if the
int returned is 0, both elements are equal
- if the
int returned is positive, first element is greater
class CustomComparator implements Comparator<String>
{
HashMap<String, Integer> map;
public CustomComparator()
{
map = new HashMap<>();
map.put("Admin", 1);
map.put("Printers", 2);
map.put("Configuration", 3);
map.put("Event Manager", 4);
map.put("Service Desk", 5);
}
public int compare(String s1, String s2) {
return map.get(s1) - map.get(s2);
}
}
class Main {
public static void main(String []args){
System.out.println("Hello World");
String[] usersList = {"Printers", "Configuration","Admin", "Service Desk", "Event Manager"};
System.out.println("Before sorting: ");
Arrays.toString(usersList);
Arrays.sort(usersList, new CustomComparator());
System.out.println("After sorting: ");
Arrays.toString(usersList);
}
}
Since Comparator<T> is a functional interface, you can also use a lambda expression and define the map in the same function:
HashMap<String, Integer> map = new HashMap<>();
map.put("Admin", 1);
map.put("Printers", 2);
map.put("Configuration", 3);
map.put("Event Manager", 4);
map.put("Service Desk", 5);
Arrays.sort(usersList, (s1, s2) -> map.get(s1) - map.get(s2));
System.out.println("After sorting:");
Arrays.toString(usersList);