Sometimes you need to do things backwards.
With a Java Map, for example, you almost always need to get a value based on its key. But every now and then you might need to get a key based on its associated value.
Hey, it happens. I get it.
And in this guide, I'll show you how to do a reverse lookup with a Java Map.
What You're Doing Here
Let's say you're developing a CRM app and you've got a Map that associates customer names with sales regions. And you'd like to get all the customers in the Southwest region.
Start by plugging in some test data:
Map<String, String> customerMap = new HashMap<String, String>(); customerMap.put("Joe Jones", "Northeast"); customerMap.put("John Jackson", "Southwest"); customerMap.put("Lief Beauregard", "Southwest"); customerMap.put("Ashton Kendall", "South"); customerMap.put("Leila Prinz", "Pacific");
That's fairly straightforward. You've got the customer's names as keys and their respective regions as values.
So at this point it's easy enough to look up a customer's region by his or her name. Just use the get() method on the Map object.
But what if you want to get all the customers associated with a particular region?
Well, you can do that as well.
Streams Come True (Say They Do)
The best way to fulfill this requirement is with the aid of a Java Stream. Go that route and you'll keep your code tight while simultaneously getting the data you're looking for.
Here's how you can accomplish that:
Set<String> customers = customerMap .entrySet() .stream() .filter(entry -> entry.getValue().equals("Southwest")) .map(Entry::getKey) .collect(Collectors.toSet());
Let me explain what's going on there.
First, the code gets the entry set from the Map object. An entry set, you'll recall from Java 101, is nothing more than a List of Entry objects.
And each Entry object associates a key with a value.
Anyway, since the entry set is in List format, you can get a Stream object from it. And that's exactly what the code above does in the third line.
Next, the code filters the stream to include only entries that match a specific criteria. In this case, the criteria is all entries with a value equal to "Southwest."
The map() method then maps each Entry object to a String object. It does that by grabbing the key value from the Entry object using a method reference (::).
Finally, the code uses the collect() method to transform the Stream object into a Set object. That will return a collection of all customers in the Southwest sales region.
If you print out the customers object to the console, you'll see this:
[John Jackson, Lief Beauregard]
And that's exactly what you'd expect to see because those two customers are associated with the Southwest sales region.
Wrapping It Up
Any questions? No?
Okay, well then it's your turn to take what you've learned here and use it in your own code.
Photo by from