[英]Converting a List of POJO into List of some other POJO in Java Stream
I have 2 POJO Foo and FooDBObj
, I fetch List of FooDBObj
from database and now I need to create List of Foo
Objects. 我有2个POJO Foo和FooDBObj
,我从数据库中获取了FooDBObj
列表,现在我需要创建Foo
对象的列表。 I need to set Id and name in FooDBObj
into Foo's BarId
and BarName
respectively. 我需要将FooDBObj
ID和名称分别设置为Foo的BarId
和BarName
。 If its in Java Stream it will be better 如果它在Java Stream中会更好
I have tried to get the list of Id's alone from below code. 我试图从下面的代码中获取Id的列表。
List<String> fooIds =FooDBObjList.stream().map(FooDBObj::getId).collect(Collectors.toList());
The above code can give me only list of Id for Foo I need all the FooDBObj.id
to be set in Foo.BarId
and FooDBObj.name
to be set in FooDBObj.BarName
上面的代码可以给我的只有编号列表Foo的我需要所有的FooDBObj.id
在设置Foo.BarId
和FooDBObj.name
中要设置FooDBObj.BarName
I guess you could simply write the mapping logic directly: 我想您可以直接直接编写映射逻辑:
Stream<Foo> = fooDBObjList.stream()
.map(db -> {
Foo foo = new Foo();
foo.setBarId(db.Id);
foo.setBarName(db.name);
return foo;
});
If Foo
already have an appropriate constructor (or a factory method like Foo.from(FooDbObj)
it could be done via method reference: 如果Foo
已经具有合适的构造函数(或Foo.from(FooDbObj)
之类的工厂方法Foo.from(FooDbObj)
则可以通过方法引用来完成:
Stream<Foo> = fooDbObjList.stream().map(Foo::from); // Factory method
….map(Foo::new) // if Foo(FooDbObj) constructor
….map(db -> new Foo(db.Id, db.name)) // if Foo(barId, barName) constructor
fooDBObjList.stream()
.map(Foo:map)
.collect(Collectors.toList());
in Foo class: 在Foo类中:
Foo map(FooDBObj dbObj) {
return Foo.builder
.id(dbObj.getId())
.name(dbObj.getName())
.build();
}
Or you can go like this too, 或者你也可以这样
fooDBObjList.stream().forEach(x -> {
Foo foo = new Foo ();
foo.setId(x.getid());
foo.setName(x.getname());
foooList.add(foo);
});
One can use below snippet:
List foo = FooDBObjList.stream().map(fooDBObj -> { Foo f = new Foo();
f.setBarName(fooDBObj.getName());
f.setBarId(fooDBObj.getId());
return f;}).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.