3

I have map of this object Map<String, List>. It is coming from backend and I wanted to sort it on Key.

Key will be any of this: CHECKING,SAVINGS, CREDIT, LOAN.

I want to sort the map in this order.

Here is my code which is not working as expected.

 private val productType: Comparator<in String> = compareBy { name ->
        productSortedOrder.indexOf(AccountProductEnum.safeValueOf(name))
    }

 private val productSortedOrder = arrayOf(AccountProductEnum.CHECKING,
        AccountProductEnum.SAVINGS,
        AccountProductEnum.CREDIT,
        AccountProductEnum.LOAN)

Here is how I am sorting the map:

accountList.groupBy { account -> account.product.name }
                        .toSortedMap(productType)

With this logic, it is printing in this order CREDIT, CHECKING, LOAN, SAVINGS I want in this sequence CHECKING, SAVINGS, CREDIT, LOAN.

How should I achieve this?

1
  • 1
    This should work. I tried duplicating it and it worked fine. It does seem a little convoluted to group by enum name and then immediately convert the names back to the enum type in order to compare them. If you grouped by the product enum type directly, your comparator could just be compareBy(productSortedOrder::indexOf), and then you can map the keys to their names afterwards if necessary. Commented Jul 7, 2020 at 13:36

0

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.