Are you developing a Spring Boot application and recently discovered that you need to retrieve values from a Map with case-insensitive keys?
Well here's some good news: you can do that.
And I'll show you how. You'll use a class you probably never heard about until you read the title of this article.
Let's get going.
Let's say you're working on a CRM app. You've got access to a Map object that associates customers with their total value of purchases in U.S. dollars.
Go ahead and get some mock data going with this code:
Map<String, Integer> map = new HashMap<>(); map.put("Janice", 100000); map.put("Jerry", 20000); map.put("Buck", 500000);
That's a fairly standard way of instantiating a Map and adding data to it.
Now run the following code:
That's going to give you a big, fat, red null in the console.
Why? Because the keys in HashMap are case-sensitive. And you tried to get Janice's numbers with a lower-case j.
So there was no match.
Fortunately, there's an easy fix for that.
An Easy Fix
Just change the Map instantiation code from the above block to this:
Map<String, Integer> map = new LinkedCaseInsensitiveMap<>();
Leave everything else the same and run that code line again.
You'll get a bright, pretty 100000 on your console.
So what happened?
Well LinkedCaseInsensitiveMap lives up to its name. It gives you a Map object with keys that are case-insensitive.
But it's only available for people using the Spring framework.
Fortunately, that's exactly what you're using if you're developing a Spring Boot application. So you'll have access to the class.
It would be nice if Java made a class like that available to people using Java without the Spring framework. But I don't think such a thing exists as of this writing.
Notice that word Linked at the beginning of the class name? That's not insignificant.
In this case, it means the Map not only gives you case-insensitive keys, but also preserves insertion order.
So if you need to keep the order of entries in the map according to how they were added, you get that for free with this class.
Not sure why the developers felt the need to throw that in but I doubt anybody's complaining.
Wrapping It Up
Now you've got a handle on how to work with a Map that's packed with case-insensitive keys.
Get busy with that LinkedCaseInsensitiveHashMap class so you can streamline your development efforts.
Photo by from