-1

I'd like to sort an ArrayList according to my logic:

        ArrayList<String> cards = new ArrayList<>(Arrays.asList("K","A","7","Q","6","J","T"));
// desired result: [6, 7, T, J, Q, K, A]

So like poker card this is the ascending order: 2,3,4,5,6,7,8,9,T,J,Q,K,A

How could I achieve it?

lipilocid
  • 87
  • 8

2 Answers2

1

Please try if this code helps you.

import java.util.*;

class CustomComparator implements Comparator<String> {
    final String ORDER= "23456789TJQKA";
    public int compare(String a, String b) {
        return ORDER.indexOf(a) -  ORDER.indexOf(b) ;
    }
}

public class SortIt {

    public static void main(String[] args) {
        List cards = new ArrayList<>(Arrays.asList("K", "A", "7", "Q", "6", "J", "T"));
        Collections.sort(cards, new CustomComparator());
        System.out.println(cards);

    }
}

Output:

[6, 7, T, J, Q, K, A]

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
1

@Niklas has answered with a clean code, and if I were you, I'd use that. This is just another answer and if the complexity is not important for you, you can use it. Maybe you get an idea for your other projects.

public List<String> sort(String[] cards) {
    for (int i = 0; i < cards.length; i++) {
        switch (cards[i]) {
            case "T":
                cards[i] = "91";
                break;
            case "J":
                cards[i] = "92";
                break;
            case "Q":
                cards[i] = "93";
                break;
            case "K":
                cards[i] = "94";
                break;
            case "A":
                cards[i] = "95";
                break;
        }
    }
    Arrays.sort(cards);
    for (int i = 0; i < cards.length; i++) {
        switch (cards[i]) {
            case "91":
                cards[i] = "T";
                break;
            case "92":
                cards[i] = "J";
                break;
            case "93":
                cards[i] = "Q";
                break;
            case "94":
                cards[i] = "K";
                break;
            case "95":
                cards[i] = "A";
                break;
        }
    }
    return Arrays.asList(cards);
}
Fred A
  • 116
  • 1
  • 6