I want to sort a Map based on values alphabetically and ignoring case sensitivity and return the list of Keys.
/**
* This method will sort allCostPlanDetailsRows based on Value in <Key,Value> pair
*
* @param sortingOrder_ whether to sort the LinkedHashMap in Ascending order or Descending order
* @return List<String> returns List of costPlanDetailsRowId in sorted order
*/
private List<String> sortCostPlanDetailRows( SortingOrder sortingOrder_ )
{
return _allCostPlanDetailRows
.entrySet()
.stream()
.sorted( sortingOrder_ == SortingOrder.DESC ? Map.Entry.<String, String>comparingByValue(Comparator.nullsFirst(Comparator.naturalOrder())).reversed() : Map.Entry.comparingByValue(Comparator.nullsFirst(
Comparator.naturalOrder())) )
.map( Map.Entry::getKey )
.collect( Collectors.toList() );
}
How can I achieve this?
Note: Suggestions are welcomed on if I can improve above piece of code.
Example: Sort a map by values Inside the method, we first created a list named capitalList from the map capitals . We then use the sort() method of Collections to sort elements of the list. The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.
HashMaps are a good method for implementing Dictionaries and directories. Key and Value can be of different types (eg - String, Integer). We can sort the entries in a HashMap according to keys as well as values.
If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values. After that get the Set of elements from the Map and convert Set into the List. Use the Collections.
Step 1: Create a TreeMap in java with a custom comparator. Step 2: Comparator should compare based on values and then based on the keys. Step 3: Put all key-value pairs from the hashmap into the treemap. Step 4: return the treemap.
Instead of using the naturalOrder
comparator, you can use String.CASE_INSENSITIVE_ORDER
:
return _allCostPlanDetailRows
.entrySet()
.stream()
.sorted( sortingOrder_ == SortingOrder.DESC ? Map.Entry.<String, String>comparingByValue(Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER)).reversed() : Map.Entry.comparingByValue(Comparator.nullsFirst(
String.CASE_INSENSITIVE_ORDER)) )
.map( Map.Entry::getKey )
.collect( Collectors.toList() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With