Tutorial :Sort Map by keys with IgnoreCase?



Question:

Well, I tested TreeMap but it doesn't take in account IgnoreCase on string comparision. I need to order lexicographically and ignoring case. Is there any other way?

Thanks, that works (TreeMap (Comparator c)). However, I have another question:

public final Comparator<Object> STR_IGN_CASE_COMP = new Comparator<Object>() {        public int compare(Object h1, Object h2) {              String s1 = h1.getId();              String s2 = h2.getId();              return s1.compareToIgnoreCase(s2);      }  }; //STR_IGN_CASE_COMP  

How can I universialize the comparator to work with different objects? assuming all have the getId() method.

Thanks, Martin


Solution:1

You want to use a Comparator in the TreeMap constructor. In particular, look at String.CASE_INSENSITIVE_ORDER.

TreeMap map = new TreeMap(String.CASE_INSENSITIVE_ORDER);  

Using Collator or a custom Comparator may work better for you in a non-English locale or if you need more complex ordering.


Solution:2

The best way would be to use a Collator. A collator is a built in class, which also implements Comparable, and therefore you can use it for your TreeMap.

With a collator, you can also control the strength of the comparision, for example, if you want to be accent-insensitive as well.

Collator stringCollator = Collator.getInstance();  stringCollator.setStrength(Collator.PRIMARY);   new TreeMap<String, String>(stringCollator)  


Solution:3

Provide it a Comparator that compares strings case ignored.

TreeMap(Comparator c)


Solution:4

If you had a list, I would say try Collections.sort() with a Comparator. You may have to roll your own Comparator that uses String.equalsIgnoreCase() instead of equals().

public static <T> void sort(List<T> list,                          Comparator<? super T> c)  

But I was on the right track. Try the TreeMap constructor that takes a Comparator:

public TreeMap(Comparator<? super K> comparator)  


Solution:5

Yes, what you want is to use the TreeMap constructor that takes a Comparator. Make a comparator that uses compareToIgnoreCase.


Solution:6

How can I universialize the comparator to work with different objects? assuming all have the getId() method.

You should be able to use a BeanComparator.


Solution:7

I suspect that you should construct your TreeMap with a custom comparator.

import java.text.Collator;  import java.util.Comparator;    class IgnoreCaseComp implements Comparator<String> {    Collator col;      IgnoreCaseComp() {      col = Collator.getInstance();        col.setStrength(Collator.PRIMARY);    }      public int compare(String strA, String strB) {      return col.compare(strA, strB);    }  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »