I'm trying to sort a list of strings. The strings contain usernames and their kills. I want to sort the list using the number of kills before username and the -. I have read about Comparator and tried some without any luck.
public class Test {
public static List<String> TOP10_Players = new ArrayList<>();
public static void AddPlayers() {
// TOP10_Players.add("[Kills]-[Username]");
TOP10_Players.add("1-Username1");
TOP10_Players.add("2-Username2");
TOP10_Players.add("3-Username3");
SortList();
}
public static void SortList() {
// Code to sort list
}
}
you can do it by using Comparator. With split("-") will seperate a single string where "-" are found and return a String[]. And then with the help of Integer.parseInt(((String) o).split("-")[0])), it will convert the first splitted String item to Integer and the Comparator can sort the list accordingly.
TOP10_Players.sort(Comparator.comparing((Object o) -> Integer.parseInt(((String) o).split("-")[0])));
Output: [1-Username1, 3-Username3, 5-Username2]
For descending order:
TOP10_Players.sort(Comparator.comparing((Object o) -> Integer.parseInt(((String) o).split("-")[0])).reversed());
Output: [5-Username2, 3-Username3, 1-Username1]