Check if value is present as key in a Map in Java



This example shows how to check if a value exists as a key in a map. Let’s say we have a ComboBox and we want to compare the selected value in the ComboBox with they keys in a map to see if it exists.

There are a few different options to do just that and the example below will show a few of them. Let’s assume we have a ComboBox with a corresponding model called comboBoxModel.

In the example above the method keySet is called on the coordinates to get a Collection (a Set) which has a method called contains where we just send in our value to look for. The method returns true if it exists, otherwise false.

In the example above we check if value exists as key in the Hashtable by using lambda expressions which is available from Java version 1.8.
We get the Stream from the keySet and filter out values that matches the selected value and call the findFirst() method. In this case it should only be one item that matches the value so we could also call the findAny() method. Both of those methods return an Optional object whether the value is found or not. Then call isPresent() on the object to check if the value is actually found. If so, call get() on it to retrieve the value.

If you don’t want to use an optional object you can instread call orElse() method and specify what value should be returned if not found. In the example above we just return null, and the if statement just do a null-check on the variable returned.







Search for more Java info on this site here:
Custom Search


Please type any questions here.