java - 迭代时如何修改除当前元素之外的所有元素

标签 java collections

我有包含标签列表的评论列表。

我想迭代我的评论列表,如果一条评论具有标签 DEPRECATE_OTHERS,我想向所有其他评论添加一个标签 DEPRECATED。

到目前为止,我已经能够想出一个过于困惑的解决方案,但我想知道是否有一些工具可以帮助我使其变得更干净:

    for (int i = 0; i < comments.size(); i++) {
        Comment comment = comments.get(i);
        for (Tag tag : comment.getTags()) {
            if(MyEnum.DEPRECATE_OTHERS.equals(tag)) {
                for(int j = 0; j < comments.size(); j++) {
                    if(j != i) {
                        comments.get(j).getTags().add(MyEnum.DEPRECATED)
                    }
                }
            }
        }
    }

OBS:我可能有多个 DEPRECATE_OTHERS,在这种情况下我想添加多个 DEPRECATED 标志

最佳答案

您可以使用几种方法来简化此代码。对于每次迭代,使用 Collection.contains() 和对象相等性,您可以将其归结为:

for (Comment comment : comments) {
    if(comment.getTags().contains(MyEnum.DEPRECATE_OTHERS))) {
        for (Comment otherComment : comments) {
            if (otherComment != comment) {
                otherComment.getTags().add(MyEnum.DEPRECATED)
            }
        }
    }
}

正如 Adam 所说,两个单独的迭代会更整洁。

关于java - 迭代时如何修改除当前元素之外的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208380/

相关文章:

java - 在 Android 上获取位置时如何解决应用程序崩溃错误?

java - 异步任务变慢问题

java - 当一个 android Activity 启动另一个 Activity 时会发生什么

Java - 行为决策 "instanceof"与标志

c# - GetEnumerator 的重载

java - org.postgresql.util.PSQLException : ERROR: relation "sequence-gen" does not exist

java - 在 GWT 项目中将 jsp 文件放在哪里?

c++ - 实例 C++ 的静态集合?

java - 如何从 Java 中的集合中弹出项目?

C# 树/集合算法