简体   繁体   中英

get list of ids from list of objects from inner list java 8

I have list of entity class:

public class Entity
{
    private long id;    
    private List<InnerEnity> data;

    public long getId() {
        return id;
    }

    public List<InnerEnity> getData() {
        return data;
    }
}

this is InnerEnity class

public class InnerEnity 
{
    private long id;    
    private String data;

    public long getId() {
        return id;
    }

    public String getData() {
        return data;
    }
}

what i need is list of InnerEnity ids. to resolve this i am trying something like that :-

List innerEnityIds = listOfEnity.stream().map(sys -> sys.getData().stream().map(obj->obj.getId().collect(Collectors.toList())));

Here you need flatMap :

List<Long> innerEnityIds = 
    listOfEnity.stream() // Stream<Entity>
               .flatMap(sys -> sys.getData().stream().map(InnerEntity::getId)) // Stream<Long>
               .collect(Collectors.toList()); // List<Long>

Or, you can break the flatMap step into flatMap + map :

List<Long> innerEnityIds = 
    listOfEnity.stream() // Stream<Entity>
               .flatMap(sys -> sys.getData().stream()) // Stream<InnerEntity>
               .map(InnerEntity::getId) // Stream<Long>
               .collect(Collectors.toList()); // List<Long>

I think this might do the trick (haven't tested it):

List<Long> innerEntityIds = listOfEnity.stream()
    .flatMap(e -> e.getData().stream()) // 1
    .map(ie -> ie.getId())  // 2
    .collect(Collectors.toList()); // 3

1) stream all the inner entities into one stream using flatMap 2) map each inner entity to its id 3) collect the id's into a list

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