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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In Java 8, the
Properties
class inherits a new method fromHashTable
calledforEach
. This new method accepts functions (functional interfaces) to be passed to it as arguments. To be more specific, it accepts the functional interfaceBiConsumer<T,U>
. This functional interface's functional method isaccept(T t, U u)
. In Java 8, all functional interfaces can be written as Lambda expressions. Therefore, here is how we would display all properties in aProperty
instance:One solution:
Rundown:
Properties
extendsHashtable<Object, Object>
which itself implementsMap<Object, Object>
;Map
has a.forEach()
method whose argument is aBiConsumer
;BiConsumer
is a functional interface;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
;Foo::printProperty
as a method reference.A shorter version would be:
At runtime, this would not make a difference. Note the type inference in the second example: the compiler can infer that
key
andvalue
are of typeObject
. Another way to write this "anonymous lambda" would have been:(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).
(not so) Side note 2: you may have noticed that
Map
's.forEach()
mentions a default implementation; this means that your customMap
implementations, or other implementations from external libraries, will be able to use.forEach()
(for instance, Guava'sImmutableMap
s). Many such methods on Java collections exist; do not hesitate to use these "new methods" on "old dogs".@fge has missed one very short version that admittedly depends on the
toString
implementation ofMap.Entry
.entrySet
is streamed and eachMap.Entry
is printed with a reference toout.println
.Map.Entry
implementations oftoString
generally returngetKey() + "=" + getValue()
.Here's another one I quite like.
entrySet
is streamed again (this time explicitly with a call tostream
).Stream#map
performs a 1:1 conversion from elements of one type to elements of another. Here, it turns aStream<Map.Entry>
in to aStream<String>
.Stream<String>
is printed.Sorted by key (makes it useful)