Java 8 Lambda按列表过滤 [英] Java 8 Lambda filter by Lists

查看:129
本文介绍了Java 8 Lambda按列表过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,我想要列出包含的过滤元素。我想用lambda表达式做这件事。

I have two list and i want filter thoose elements which are both list contains. And i want to do this with lambda expression.

用户getName和客户端getUserName都返回String。

Users getName and Clients getUserName both are return with String.

以下是我的示例代码:

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());

但效率很低,因为它是O(m * n)。你最好创建一组可接受的名字:

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.

这篇关于Java 8 Lambda按列表过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆