简体   繁体   English

如何将包含字符串列表(内部列表)的对象列表转换为字符串列表

[英]How to convert List Of Objects containing list of String (inner list) to List of String

I have class like我有 class 喜欢

public class RoleAccess {

    private String roleId;

    private List<String> apiIdList;

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    public List<String> getApiIdList() {
        return apiIdList;
    }

    public void setApiIdList(List<String> apiIdList) {
        this.apiIdList = apiIdList;
    }

}

I want to create a new list which will add all apiIdlist from roleaccess我想创建一个新列表,它将添加来自 roleaccess 的所有 apiIdlist

List<String> apiIdList = new ArrayList<>();
for (RoleAccess roleAccess : roleAccessList) {
            if (roleAccess.getApiIdList() != null) {
                apiIdList.addAll(roleAccess.getApiIdList());
            }
        }

How can we do with stream api or which is best solution to do this?我们如何处理 stream api 或者这是最好的解决方案?

I checked normal object list to list but I want to list of object and inner list to list I tried this我检查了正常的 object 列表,但我想列出 object 和内部列表我试过这个

  List<String> apiIdList = roleAccessList.stream()
                          .map(RoleAccess::getApiIdList)
                          .collect(ArrayList::new, List::addAll, List::addAll);

Use flatMap instead of map : 使用flatMap代替map

List<String> apiIdList = roleAccessList.stream()
    .flatMap(e -> e.getApiIdList().stream())
    .collect(Collectors.toList());

Please take a look on the link for more info about flatMap . 请在链接上查看有关flatMap更多信息。

List<String> apiIdList = roleAccessList.stream()
                       .map(RoleAccess::getApiIdList)
                       .filter(Objects::nonNull)
                       .flatMap(Collection::stream)
                       .collect(Collectors.toList());

An alternate solution would be: 一种替代解决方案是:

List<String> apiIdList = roleAccessList.stream()
        .flatMap(a -> a.getApiIdList().stream()) // flat map the apiIds from list
        .filter(Objects::nonNull) // use only not null
        .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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