Following the same principles found in filtering a map by entries and filtering a map by values, this example will show how to filter a map by Map.key while using java, java 8 and guava. Each of the snippets below will use a predefined map created in the @setup where the entries resemble a month. The Map.key is the integer month of year (1=January) and the value represents the month spelled out. A comparable example demonstrates how to filter a map by keys in groovy.
Straight up Java
The core jdk lack the mechanics for filtering a map by Map.key until java 8. As shown in the snippet below, the only effective way is to iterate over the Map.entrySet using a for loop and then applying criteria in an if statement, in this case checking if entry.key is less than four or finding months contained in the first quarter.
The snippet below will show how to filter a map by keys using java 8. Using the powerful streams api, we will call entrySet.stream and filter months within the first quarter. We created this java.util.function.predicate by using a lambda expression. Then using Collectors.toMap we will map each element in the stream back into a map.