首页 > 解决方案 > way to find the List of all ids in a list of entities from inner object with java 8

问题描述

I have an entity:

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

    public long getId() {
        return id;
    }

    public InnerEnity getData() {
        return data;
    }
}

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 tried something like that :-

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

标签: javacollectionsjava-8java-stream

解决方案


You just need to map the entity to its inner entity's(data) id as :

List<Long> innerEnityIds = listOfEnity.stream()
        .map(entity -> entity.getData().getId()) // <<< this
        .collect(Collectors.toList());

推荐阅读