2

There is a list of String currency ISO codes in random order: CHF, USD, AUD, EUR, 0995, AED... etc.

Is there an algorithm to sort it in the following order: first should go only main currencies (USD, CHF, EUR) - in exactly this order, then alphabetically all other currencies, then all numeric currency codes?

As of now i do it in 3 steps by simply creating 3 separate lists, sorting them accordingly and then making list.addAll. Would appreciate any help

1 Answer 1

6

Creating a custom comparator would be the ideal way to tackle this scenario.

public class CurrencyComparator implements Comparator<String> {

    public static void main(String[] args) {
        List<String> currencyList = Arrays.asList("CHF", "USD", "AUD", "EUR", "0995", "AED");
        currencyList.sort(new CurrencyComparator());
        currencyList.forEach(System.out::println);
    }

    private int getTypeOrder(String cur) {
        switch (cur) {
            case "USD":
                return 0;
            case "CHF":
                return 1;
            case "EUR":
                return 2;
            default:
                return cur.matches("[A-Za-z]*") ? 3 : 4;
        }
    }

    @Override
    public int compare(String cur1, String cur2) {
        int typeOrder1 = getTypeOrder(cur1);
        int typeOrder2 = getTypeOrder(cur2);
        if (typeOrder1 != typeOrder2) {
            return Integer.compare(typeOrder1, typeOrder2);
        }
        return cur1.compareTo(cur2);
    }
}

It will produce the below output

USD
CHF
EUR
AED
AUD
0995
Sign up to request clarification or add additional context in comments.

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.