5

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.

0

1 Answer 1

8

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() );
Sign up to request clarification or add additional context in comments.

2 Comments

thanks just one doubt, Will that be applicable for only Null values or for all other values as well?
You will have the nulls first, as you're using Comparator.nullsFirst. All the strings that aren't nulls will then be sorted regardless of their case.

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.