I am trying to enhance my current code using java 8
I have two list of pojos
class A{
long id;
String name;
Sting age;
// getters setters
}
class B{
long id;
String address;
String city;
// getters setters
}
required class:
class C{
long id;
String name;
Sting age;
String address;
String city;
// getters setters
}
i have list<A>
and List<B>
, and require final List<C>
. I have completed this using for loops and everything. but i now want to streamline in using java 8 functionalitis.
Any help is very much appreciated.
EDIT
List<C> cList=new ArrayList<>();
C obj=new C();
for(A aa: aList){
C obj=new C();
obj.setId(a.getId);
obj.setName(a.getName);
obj.setAge(a.getAge);
for(B bb: bList){
if(aa.getId==bb.getId(){
obj.setAddress(bb.setAddress);
obj.setCity(bb.setCity);
}
}
cList.add(obj);
}
if you want just transfer your code to streams, you can:
List<C> collect = aList.stream()
.map(a -> {
C obj = new C();
obj.setId(a.getId());
obj.setName(a.getName());
obj.setAge(a.getAge());
bList.stream()
.filter(b -> a.getId() == b.getId())
.findFirst()
.ifPresent(b -> {
obj.setAddress(b.getAddress());
obj.setCity(b.getCity());
});
return obj;
}).collect(toList());
But it will be better to introduce map for bList
and use it as a lookup latter.
Map<Long, B> map = bList.stream()
.collect(Collectors.toMap(B::getId, b -> b));
List<C> collect = aList.stream()
.map(a -> {
C obj = new C();
obj.setId(a.getId());
obj.setName(a.getName());
obj.setAge(a.getAge());
if (map.containsKey(a.getId())) {
B b = map.get(a.getId());
obj.setAddress(b.getAddress());
obj.setCity(b.getCity());
}
return obj;
}).collect(toList());