简体   繁体   中英

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. I need to set Id and name in FooDBObj into Foo's BarId and BarName respectively. If its in Java Stream it will be better

I have tried to get the list of Id's alone from below code.

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

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:

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 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM