Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map key value to an object in Java 8 stream

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.

like image 252
fastcodejava Avatar asked Dec 04 '22 19:12

fastcodejava


1 Answers

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.

like image 54
Ousmane D. Avatar answered Dec 21 '22 22:12

Ousmane D.