简体   繁体   中英

How to retrieve a list from another object that is in the list using stream

I have a little problem. From earlier steps I get this list:

List<Foo> fooList;

I need now get all id to separate list:

List<Integer> newListIds;

Is it possible to do it using streams, possibly as otherwise the easiest way to do it?

My clases:

public class Foo {

   List<Bar> barList;

   //getter, setter
} 

public class Bar {

   private Integer id;

   //geter, setter 
}

You can do it using flatMap:

fooList.stream()
           .map(foo -> foo.barList)
           .flatMap(List::stream)
           .map(bar -> bar.id)
           .collect(Collectors.toList());

Or using method reference for getter and setter:

fooList.stream()
           .map(Foo::getBarList)
           .flatMap(List::stream)
           .map(Bar::getId)
           .collect(Collectors.toList());

Just try this code:

List newListIds = new ArrayList ();

    for(Foo item : fooList){
       newListIds.addAll(item.barList.stream()
                               .map(Bar::GetId)
                               .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