Kishore Chandran
Kishore Chandran

Reputation: 477

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

Upvotes: 1

Views: 3118

Answers (4)

erolkaya84
erolkaya84

Reputation: 1849

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

Upvotes: 0

Mak
Mak

Reputation: 1078

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

Upvotes: 1

Bhavik Shah
Bhavik Shah

Reputation: 84

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

Upvotes: -1

jensgram
jensgram

Reputation: 31508

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

Upvotes: 3

Related Questions