如何使用Java 8和lambdas打印JVM的系统属性? [英] How would I print the JVM's system properties using Java 8 and lambdas?
问题描述
您可以使用属性实例的java /郎/ System.html#的GetProperties - > System.getProperties()
;你将如何使用Java 8代码将所有属性打印到控制台?
You can obtain a Properties
instance of the JVM properties using System.getProperties()
; how would you go about using Java 8 code to print all properties to the console?
推荐答案
一个解决方案:
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);
}
}
破旧:
-
属性
extendsHashtable< Object,Object>
本身实现地图<对象,对象>
; -
地图
有.forEach()
方法,其参数为BiConsumer
; -
BiConsumer
是功能界面; - 静态方法
printProperty()
类Foo
碰巧有相同的签名为BiConsumer< Object,Object>
:其返回值为void
,其第一个参数为对象
,它的第二个参数是Object
; - 因此我们可以使用
Foo :: printProperty
作为方法参考。
Properties
extendsHashtable<Object, Object>
which itself implementsMap<Object, Object>
;Map
has a.forEach()
method whose argument is aBiConsumer
;BiConsumer
is a functional interface;- static method
printProperty()
of classFoo
happens to have the same signature as aBiConsumer<Object, Object>
: its "return value" isvoid
, its first argument isObject
, its second argument isObject
; - we can therefore use
Foo::printProperty
as a method reference.
更短的版本是:
public final class ShorterFoo
{
public static void main(final String... args)
{
System.getProperties()
.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
在运行时,这不会产生任何影响。请注意第二个示例中的类型推断:编译器可以推断键
和值
的类型为对象
。编写这个匿名lambda的另一种方法是:
At runtime, this would not make a difference. Note the type inference in the second example: the compiler can infer that key
and value
are of type Object
. Another way to write this "anonymous lambda" would have been:
(Object key, Object value) -> System.out.println(key + ": " + value)
(不是这样)旁注:即使它有点过时,你真的想看这个视频(是的,这是一个小时的长度;是的,值得一看。)
(not so) Side note: even though it is a little outdated, you really want to watch this video (yes, it's one hour long; yes, it is worth watching it all).
(不是这样)旁注2:您可能已经注意到 Map
的 .forEach()
提到默认实现;这意味着您的自定义 Map
实现或外部库的其他实现将能够使用 .forEach()
(例如,Guava的 ImmutableMap
s)。存在许多关于Java集合的此类方法;不要犹豫在老狗上使用这些新方法。
(not so) Side note 2: you may have noticed that Map
's .forEach()
mentions a default implementation; this means that your custom Map
implementations, or other implementations from external libraries, will be able to use .forEach()
(for instance, Guava's ImmutableMap
s). Many such methods on Java collections exist; do not hesitate to use these "new methods" on "old dogs".
这篇关于如何使用Java 8和lambdas打印JVM的系统属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!