2

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
    }
}

2 Answers2

5

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]

StackD
  • 66
  • 6
2

I suggest do it step by step:

  1. Create map with id and kills,
  2. Using suggestion from following topic sorted this map,
  3. Save keys to ArrayList,

For example (draft, not checking):

public static void SortList() {
    Map<String, Value> map = new HashMap();
    for(String playerAndKill: TOP10_Players) {
        String parts = playerAndKill.split('-');
        int kills = Integer.parseInt(parts[0]);
        map.put(playerAndKill, kills); 
    }
    TOP10_Players = sortByValue(map).keySet();
}


public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
    list.sort(Entry.comparingByValue());

    Map<K, V> result = new LinkedHashMap<>();
    for (Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59