One solution:
public final class Foo { private static void printProperty(final Object key, final Object value) { System.out.println(key + ": " + value); } public static void main(final String... args) { System.getProperties().forEach(Foo::printProperty); } }
Run over:
Properties extends Hashtable<Object, Object> which itself implements Map<Object, Object> ;Map is the .forEach() method, whose argument is BiConsumer ;BiConsumer is a functional interface ;- The static
printProperty() method of the Foo class has the same signature as BiConsumer<Object, Object> : its "return value" is void , its first argument is Object , and the second is Object ; - therefore we can use
Foo::printProperty as a reference to a method.
The shortened version will be:
public final class ShorterFoo { public static void main(final String... args) { System.getProperties() .forEach((key, value) -> System.out.println(key + ": " + value)); } }
At runtime, this will not matter. Notice the type inference in the second example: the compiler can determine that key and value are of type Object . Another way to write this โanonymous lambdaโ would be:
(Object key, Object value) -> System.out.println(key + ": " + value)
(not so) Note: even if it's a little outdated, you really want to watch this video (yes, it lasts one hour; yes, it's worth it).
(not this way). Note 2: you may have noticed that Map .forEach() mentions the default implementation ; this means that your custom Map implementations or other implementations from external libraries will be able to use .forEach() (e.g. Guava ImmutableMap s). There are many such methods in Java collections; Feel free to use these "new methods" on "old dogs".
fge
source share