Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-8: How to sort Map (based on values) using Map.Entry#comparingByValue while ignoring case sensitivity?

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.

like image 680
Neeraj Jain Avatar asked May 29 '17 06:05

Neeraj Jain


People also ask

How sort a Map based on its values in Java?

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.

Can we sort a Map based on value?

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.

How do you sort a given HashMap on the basis of 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.

How do you sort a Map by key value?

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.


1 Answers

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() );
like image 75
Mureinik Avatar answered Oct 26 '22 22:10

Mureinik