Mapping Maps With Method References

I just learned about “method reference” notation in Java 8 thanks to Intellij IDEA code hints.

Consider the following code:

public class MapMap
{
   Map<String, String> map;
   
   public static void map(Object key, Object value)
   {
      System.out.println(key + ":" + value);
   }
   
   public void mapmap()
   { //...see implementations below }
}

I knew this:

/* loop */ 
for (Map.Entry entry: map.entrySet()) 
{ 
  map(entry.getKey(), entry.getValue()); 
}

could be replaced with this:

/* lambda expression */ 
map.forEach((key, value) -> map(key, value);

but I did not know about this:

/* method reference */ 
map.forEach(MapMap::map);

See the full gist here


import java.util.Map;
public class MapMap
{
Map<String, String> map;
public static void map(Object key, Object value)
{
System.out.println(key + ":" + value);
}
public void mapmap()
{
/* loop */
for (Map.Entry entry: map.entrySet())
{
map(entry.getKey(), entry.getValue());
}
/* lambda expression */
map.forEach((key,value) -> {
map(key, value);
});
/* simplified lambda */
map.forEach((key,value) -> map(key, value));
/* method reference */
map.forEach(MapMap::map);
}
}

view raw

MapMap.java

hosted with ❤ by GitHub

 

See here for the official documentation on method references:

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html