gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:51:59 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com