Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java – Combine Multiple Collections

I have this piece of code, that I want to refactor using more the Java 8 approach, but I know that there are several options to do this: concat() Java 8 Stream API , flatMap() Java 8 Stream API , Using Guava, Using Apache Commons Collections, CompletableFuture.... I would like to know if there is a best practice to do this

List<User> users = new ArrayList<User>();    
for (Restaurant restaurant : restaurants) { 
    users.addAll(userService.getClients(restaurant.getId())
                            .parallelStream()
                            .filter(us -> !alreadyNotifiedUserIds.contains(us.getId())))
                            .collect(Collectors.toList());  
}
like image 623
carles xuriguera Avatar asked Jul 10 '26 23:07

carles xuriguera


1 Answers

Something like this?

List<User> users = restaurants.parallelStream()
    .flatMap(r -> userService.getClients(r.getId()).stream())
    .filter(us -> !alreadyNotifiedUserIds.contains(us.getId()))
    .collect(Collectors.toList());  
like image 75
David Pérez Cabrera Avatar answered Jul 13 '26 12:07

David Pérez Cabrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!