How to write list filtering and displaying lambda to list
This is the source:
List<Role> managedRoles = new ArrayList<>();
for (Role role : roles) {
if (role.getManagedRole() != null) { // a list of Role.
managedRoles.addAll(role.getManagedRole());
}
}
This is what I want:
managedRoles = roles.stream().filter(r -> r.getManagedRole() != null).map(role -> role.getManagedRole()).collect(); // how to addAll ?
But role.getManagedRole() is a List<Role>
I think we need some function like addAll
. So how do you do this in Lambda?
+3
source to share
2 answers
You need to use flatMap
instead map
to flatten everything List<Role>
returned role.getManagedRole()
by one Stream<Role>
.
List<Role> managedRoles =
roles.stream()
.filter(r -> r.getManagedRole() != null)
.flatMap(role -> role.getManagedRole().stream())
.collect(Collectors.toList());
+5
source to share
managedRoles = roles.stream() .filter(r -> r.getManagedRole() != null) .flatMap(role -> role.getManagedRole()) .collect(Collectors.toList());
to create as a list or try this example to add elementrs to an existing list
List<String> destList = Collections.synchronizedList(
new ArrayList<>(Arrays.asList("foo")));
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");
newList.stream()
.collect(Collectors.toCollection(() -> destList));
System.out.println(destList);
0
user7739962
source
to share