java - 使用 Java 8 检查数组中是否存在元素

标签 java arrays java-8

我有一个 DTO,其中包含一个列表,我在其中添加或删除一些项目,在我的 DAO 中,当我获得此列表时,我想将其与现有列表进行比较,因此所有不存在于该列表中的新项目旧列表将被添加,旧列表中不存在于 dto 列表中的项目将被删除。 例如,这是列表中已存在的项目:

[a,b,c]

dto 中的列表包含以下内容:

[b,d]

因此,在这种情况下,[d] 将被插入,[a][c] 将被删除。

有一种方法,我可以删除旧列表,然后添加 DTO 列表中的所有元素,但我不希望这样。

这是我尝试过的:

public Role updateRoleDTO(final RoleDTO roleDTO) {
    //...
    //... Some code
    //...
    boolean profilExist = false;
    RoleProfil roleProfil = null;

    // Add non existing profils
    for (Profil profil : roleDTO.getProfils()) {
        profilExist = false;
        roleProfil = new RoleProfil();
        for(Profil oldProfil : oldProfilsList){
            if(profil.getId().equals(oldProfil.getId())){
                profilExist = true;
                break;
            }
        }
        if(!profilExist){
            roleProfil.setRoleId(insertedRole);
            roleProfil.setProfilId(profil);
            roleProfilDAO.insert(roleProfil);
        }
    }

    //Remove existing profils that are not in the updated Role
    for(Profil oldProfil : oldProfilsList){
        profilExist = false;
        for (Profil profil : roleDTO.getProfils()) {
            if(oldProfil.getId().equals(profil.getId())){
                profilExist = true;
                break;
            }
        }
        if(!profilExist){
            roleProfilDAO.delete(roleProfilDAO.findRoleProfilByRoleIdAndProfilId(roleDTO.getRoleId(), oldProfil.getId()));
        }
    }

因此,第一次我将查看旧列表是否包含 DTO 列表中的项目,如果不包含,我将添加它。 第二次,我将查看 DTO 列表中是否包含旧列表中的项目,如果不包含,我将删除它。

在这种方法中,我创建了两个循环,每个循环都包含一个实习循环,看起来太长了。

我没有其他方法可以做到这一点吗?或者使用 Java 8 流会让它看起来更好?

最佳答案

如果你可以将你的数据结构重新建模为一个集合(并且由于你通过 id 进行比较,似乎你可以通过使 Profil 的 hashCode/equals 这样做来做到这一点),你可以使用 Guava 的 Sets 类轻松完成它:

    Set<String> oldSet = Sets.newHashSet("a", "b", "c");
    Set<String> newSet = Sets.newHashSet("b", "d");


    Sets.SetView<String> toRemove = Sets.difference(oldSet, newSet);
    Sets.SetView<String> toInsert = Sets.difference(newSet, oldSet);
    Sets.SetView<String> toUpdate = Sets.intersection(oldSet, newSet);

或者使用 Java 8 的 Streams API:

    Set<String> oldSet = new HashSet<>(Arrays.asList("a", "b", "c"));
    Set<String> newSet = new HashSet<>(Arrays.asList("b", "d"));

    Stream<String> toRemove = oldSet.stream().filter(e -> !newSet.contains(e));
    Stream<String> toInsert = newSet.stream().filter(e -> !oldSet.contains(e));
    Stream<String> toUpdate = oldSet.stream().filter(newSet::contains);

关于java - 使用 Java 8 检查数组中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46243765/

相关文章:

Java在Linux上使用su切换用户

java - 如何使用 JAVA 或任何脚本定期自动更改 mysql 密码?

java - 如何针对特定场景正确使用Apache Camel?

python - 使用 python/numpy reshape 数组

java - java获取随机生成数组的最小值和最大值

Android:获取字符串数组中使用的字符串资源的名称

java - 最适合存储日期和时间的 SQL 和 Java 数据类型

java - @CreationTimestamp 和@UpdateTimestamp 不适用于 LocalDateTime

java - 如何正确从mysql数据库中选择数据?结果集错误

java - 通过使用条件嵌套的列表元素将其与另一个列表匹配来过滤对象