f



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

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?  Thus, performing:

a.contains("bob")
a.contains("BoB")
a.contains("BOB")

would all yield the same result?


Thanks for your time.  Cheers,

Matt
--
0
Matt
3/15/2007 3:42:08 AM
comp.lang.java 3285 articles. 1 followers. Post Follow

1 Replies
1389 Views

Similar Articles

[PageSpeed] 21

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
0
Laie
4/10/2007 7:58:18 AM
Reply: