Search code examples
sortingarraylistcollectors

Sorting ArrayList on collectors function


I did the code below to have a dropdown box with all the currencies code.

List<String> currencies = Currency.getAvailableCurrencies().stream() .map(currency -> currency.getCurrencyCode()) .collect(Collectors.toList());

However, my output is unsorted.

Someone could give me a hand to sort the ArrayList(Currencies) on the code below?

Appreciate any help =)


Solution

  • You can sort by adding .sorted() into your stream. This will sort the list on it's natural order

    List<String> currencies = Currency.getAvailableCurrencies().stream().map(currency -> currency.getCurrencyCode()).sorted().collect(Collectors.toList());
    

    When you want something more advanced than natural ordering, or you want to order an object, you can simply pass a Comperator as argument to the sorted method.

    For example if you want the list to be in reverse order

    List<String> currencies = Currency.getAvailableCurrencies().stream().map(currency -> currency.getCurrencyCode()).sorted(Comparator.reverseOrder()).collect(Collectors.toList());