3

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
  • 1
    so ... what is it you tried? basically, it's just a compareTo on Strings Commented Nov 10, 2020 at 13:47
  • compareTo on Strings is not working if you have 1-user1 and 10-user2 (because 10-user2 is the first). Commented Nov 10, 2020 at 13:57

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.