我有包含标签列表的评论列表。
我想迭代我的评论列表,如果一条评论具有标签 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/