I have two list and i want filter thoose elements which are both list contains. And i want to do this with lambda expression.
Users getName and Clients getUserName both are return with String.
Here is my sample code:
List<Client> clients = new ArrayList<>();
List<User> users = new ArrayList<>();
List<Client> results = new ArrayList<>();
for (Client user : users) {
for(Client client: clients){
if(user.getName().equals(client.getUserName())){
result.add(client);
}
}
}
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.