如何使用Java 8和lambdas打印JVM的系统属性? [英] How would I print the JVM's system properties using Java 8 and lambdas?

查看:137
本文介绍了如何使用Java 8和lambdas打印JVM的系统属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用属性实例的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);
    }
}

破旧:


  • 属性 extends Hashtable< Object,Object> 本身实现地图<对象,对象> ;

  • 地图 .forEach() 方法,其参数为 BiConsumer ;

  • BiConsumer 功能界面;

  • 静态方法 printProperty() Foo 碰巧有相同的签名为 BiConsumer< Object,Object> :其返回值为 void ,其第一个参数为对象,它的第二个参数是 Object ;

  • 因此我们可以使用 Foo :: printProperty 作为方法参考。

  • Properties extends Hashtable<Object, Object> which itself implements Map<Object, Object>;
  • Map has a .forEach() method whose argument is a BiConsumer;
  • BiConsumer is a functional interface;
  • static method printProperty() of class Foo happens to have the same signature as a BiConsumer<Object, Object>: its "return value" is void, its first argument is Object, its second argument is Object;
  • 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 ImmutableMaps). Many such methods on Java collections exist; do not hesitate to use these "new methods" on "old dogs".

这篇关于如何使用Java 8和lambdas打印JVM的系统属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆