Java 8 flatmap , stream,collect -
i have situation have
class { private b b; public b getb() { return b; } }
and class b
class b { private list<c> c; public list<c> getlistc() { return c; } }
now class c contains 2 instance variables
class c { private int id; private string name; public int getid() { return id; } public string getname() { return name; } }
now want achieve below using java 8
list<c> newlistc = a.getb().getlistc(); map<integer, string> map = new hashmap<>(); for(c c : newlistc) { map.put(c.getid,c.getname()); }
i have tried many time every time face different problems. code:
optional<a> a=optional.of(new a()); map<integer, string> map= a.map(a::getb) .flatmap(b -> b.getlistc() .stream() .collect(collectors.tomap( c::getid, c::getname ) ) );
error message :
error:(164, 33) java: incompatible types: no instance(s) of type variable(s) u,r,a,capture#1 of ?,t,k,u exist java.util.optional<u> conforms java.util.map<java.lang.integer,java.lang.string>
thanks in advance
you can’t flatmap
optional
map
; function has return optional
. on other hand, since function doesn’t return optional
, flatmap
unnecessary , ordinary map
do:
map<integer, string> map = optional.of(new a()) .map(a::getb) .map(b -> b.getlistc().stream().collect(collectors.tomap(c::getid, c::getname))) .orelse(collections.emptymap());
but since result of new a()
can’t null (and using of
instead of ofnullable
acknowledges this), indirect processing @ beginning of chain unnecessary:
map<integer, string> map = optional.ofnullable(new a().getb()) .map(b -> b.getlistc().stream().collect(collectors.tomap(c::getid, c::getname))) .orelse(collections.emptymap());
but note nullability of result of getb
handled, function passed next mapping step unconditionally invokes stream()
on list returned getlistc
. returning null
list
expected bad coding style anyway; can return empty list represent absence of values.
maybe confusion stems stream
based alternative solution:
map<integer, string> map = stream.of(new a().getb()) .filter(objects::nonnull) .flatmap(b -> b.getlistc().stream()) .collect(collectors.tomap(c::getid, c::getname));
here, stream consisting of @ 1 element created, followed flatmap
ing items of list returned getlistc
…
Comments
Post a Comment