Here are two examples. Both print the key based on the correspondence in the value properties.
private static void printMatchingEntriesUsingALoop(Map<String, Map<String, String>> resMap, String key, String value) { for (Map.Entry<String, Map<String, String>> entry : resMap.entrySet()) if (value.equals(entry.getValue().get(key))) System.out.println(entry.getKey()); } private static void printMatchingEntriesUsingGuava(Map<String, Map<String, String>> resMap, final String key, final String value) { Predicate<Map<String, String>> keyValueMatch = new Predicate<Map<String, String>>() { @Override public boolean apply(@Nullable Map<String, String> stringStringMap) { return value.equals(stringStringMap.get(key)); } }; Maps.EntryTransformer<String, Map<String, String>, Void> printKeys = new Maps.EntryTransformer<String, Map<String, String>, Void>() { @Override public Void transformEntry(@Nullable String s, @Nullable Map<String, String> stringStringMap) { System.out.println(s); return null; } }; Maps.transformEntries(Maps.filterValues(resMap, keyValueMatch), printKeys); } public static void main(String... args) { Map<String, Map<String, String>> resMap = new TreeMap<String, Map<String, String>>(); printMatchingEntriesUsingALoop(resMap, "first", "mike"); printMatchingEntriesUsingGuava(resMap, "first", "mike"); }
One uses a loop and one uses Guava.
While the first one works best, you must decide which one is the easiest to understand and save.
Some suggestions from @missingfaktor. You should use your own opinion, but he has well covered some problems.
- a lot of code duplication.
- special case processing.
- More cyclic complexity.
- More likely to make a mistake as a result of the first three bullets.
- Hard to execute code.
Imagine that you are a new developer who must support this software. Who would you like to face?