Java 14 Record and Map.Entry 📎
import java.util.Map;
public record Developer(String language, int age) {
public Developer(Map.Entry<String, Integer> entry) {
this(entry.getKey(), entry.getValue());
}
}
...an Map.Entry of Java's Map
:
var developers = Map.of(
"java", 25,
"javascript", 24,
"ruby", 30);
...can be directly converted into a record
instance:
developers.entrySet().
stream().
map(Developer::new).
forEach(System.out::println);
The snippet prints the following output:
Developer[language=java, age=25]
Developer[language=javascript, age=24]
Developer[language=ruby, age=30]
See it in action and from scratch in 3 minutes:
A Java Record can also come with additional methods / logic:
public record Developer(String language, int age) {
//...
public String nicerOutput() {
return "I'm a " + this.language() + " developer and " + this.age() + " old";
}
}
...and used inside the stream:
developers.entrySet().
stream().
map(Developer::new).
map(Developer::nicerOutput).
forEach(System.out::println);
The code above prints:
I'm a javascript developer and 24 old
I'm a ruby developer and 30 old
I'm a java developer and 25 old