使用Java Stream迭代集合集合?

时间:2015-08-28 10:55:40

标签: java collections java-8 java-stream

如何使用Java 8 Stream API重构此代码?

for (Role role: user.getRoles()) {
    for (Privilege privilege: role.getPrivileges()) {
        System.out.println(privilege.getName());
    }
}

试着这样:

user.getRoles().stream()
               .map(role -> role.getPrivileges())
               .forEach(privelege -> System.out.println(privelege.getName()));

1 个答案:

答案 0 :(得分:2)

您可以合并.flatMap.map

user.getRoles()
    .stream()
    .flatMap(role -> role.getPrivileges().stream())
    .map(Privilege::getName)
    .forEach(System.out::println)