删除另一个foreach中的项目表单foreach循环并使用相同的列表 [英] Removing an item form foreach loop that is in other foreach and use the same list

查看:145
本文介绍了删除另一个foreach中的项目表单foreach循环并使用相同的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从位于另一个foreach中的foreach中的列表中删除对象,以不检查具有相同名称(但该对象中其他值不同)的对象.

I need to remove object from list that is in foreach that is in another foreach to not check objects with the same name (but different other values in that object).

for (Foo foo : fooList) {
    // some code
      for (Foo foo2 : fooList){
        if (foo2.getName() == foo.getName()) {
          // some code that stores and manipulates values from foo2
          fooList.remove(foo2);
        }
      }
      //some code that using values from many foos with the same name
    } 

当然这不起作用.

我正在尝试使用Iterator

I was trying do something with Iterator

Iterator<Foo> iterator = fooList.iterator();

while (iterator.hasNext()) {
      Foo foo = iterator.next();
      // some code
      while (iterator.hasNext()){
        Foo foo2 = iterator.next();
        if (foo2.getName() == foo.getName()) {
          // some code that stores and manipulates values from foo2
          iterator.remove();
        }
      }
      //some code that using values from many foos with the same name
    }

但是这也不做... 使用Iterator<Foo> iterator = Iterables.cycle(fooList).iterator();也不是一个好主意.

but this not do the thing either... using Iterator<Foo> iterator = Iterables.cycle(fooList).iterator(); was not a good idea too.

我将不胜感激!

推荐答案

使用

Use List::removeAll

Do it as follows:

List<Foo> toBeRemoveList = new ArrayList<Foo>();
for (Foo foo : fooList) {
    // some code
    for (Foo foo2 : fooList) {
        if (foo2.getName().equals(foo.getName()) && !toBeRemoveList.contains(foo2)) {
            // some code that stores and manipulates values from foo2
            toBeRemoveList.add(foo2);
        }
    }
    // some code that using values from many foos with the same name
}
fooList.removeAll(toBeRemoveList);

确保使用s1.equals(s2)s1s2进行比较;而不是使用s1 == s2(您的操作方式).

Make sure you use s1.equals(s2) to compare s1 with s2; rather than using s1 == s2 (the way you have done).

这篇关于删除另一个foreach中的项目表单foreach循环并使用相同的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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