Re: Case-insensitive collections (sets, maps, etc.)



On Wed, 14 Mar 2007 22:42:08 -0500, Matt wrote:

I have to believe I'm not the first person to have this question.
However, I'm not having any luck finding an answer.

I'm using Java 1.5. Say I have the following:

Set<String> a = new HashSet<String>();
Map<String, Object> b = new TreeMap<String, Object>();

Assume somewhere these are populated.

When I check the set for a string using a.contains("bob"), the method is
checking using a case-sensitive search. Similarly, if I did
b.containsKey("tom"), it's case-sensitive.

Is it possible to get these methods to perform a comparison
case-insensitively?

TreeSet and TreeMap allow you to pass in a Comparator to the constructor.
This Comparator will dictate which objects should be considered equal.
For case-insensitivity, user String.CASE_INSENSITIVE_ORDER .

Set<String> set = new TreeSet<String> (String.CASE_INSENSITIVE_ORDER);
// now populate the set
Map<String, Object> map =
new TreeMap<String,Object>(String.CASE_INSENSITIVE_ORDER);
// now populate the map

Please note that neither TreeSet nor TreeMap are synchronized, so you need
to make them thread-safe yourself.

HTH,
La`ie Techie
.



Relevant Pages

  • Re: Help with sorting values in a TreeMap
    ... > the map is an AccountView object whose 'getKey' method returns the ... > I use TreeMap so that they sort nicely by the account number. ... When you construct a TreeMap with a Comparator, ... The objects that it would be comparing _are_ the keys that you described, ...
    (comp.lang.java.programmer)
  • Re: Sorting TimeZone
    ... Map map = ... However I was replying to your statement "'TimeZone' can easily be a map key, yes, even for a 'TreeMap'. ... and a specified Comparator as somehow weird ...
    (comp.lang.java.programmer)
  • Re: [00/41] Large Blocksize Support V7 (adds memmap support)
    ... populate 1 << N ptes when mmapping a file? ... I don't have to populate them, I could just map one at time. ... If I could break backwards compatibility ...
    (Linux-Kernel)
  • RE: keeping the file name while checking w/ LWP
    ... >Use map() together with splitto populate a hash. ... Brian Volk wrote: ...
    (perl.beginners)
  • Re: TreeMap and Comparator question
    ... Comparator to a TreeMap, it must comparekeys, you can't compare ... You might want to use a SortedSet for the sorting and another map for the key lookup. ... You should be alright with HashMap and TreeMap, ...
    (comp.lang.java.programmer)