Let's say I have this code:
Map<String, String> map;
// later on
map.entrySet().stream().map(MyObject::new).collect(Collectors.toList());
And I have a MyObject
Constructor
which takes two arguments of type String
.
I want to be able to do this but I cannot.
I know I can do e -> new MyObject(e.getKey(), e.getValue())
but prefer MyObject::new
.
Similar code works for Set<String>
and List<String>
with one argument constructor of MyObject
class.
use a lambda:
map.entrySet()
.stream()
.map(e -> new MyObject(e.getKey(), e.getValue()))
.collect(Collectors.toList());
otherwise the only way to use a method reference is by creating a function as such:
private static MyObject apply(Map.Entry<String, String> e) {
return new MyObject(e.getKey(), e.getValue());
}
then do something like:
map.entrySet()
.stream()
.map(Main::apply)
.collect(Collectors.toList());
Where Main
is the class containing the apply
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With