首页 > 解决方案 > 删除其他 foreach 中的项目形式 foreach 循环并使用相同的列表

问题描述

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

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 做点什么

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();也不是一个好主意。

我将不胜感激任何帮助!

标签: javalistforeach

解决方案


如果您只需要从fooListby 特定属性中删除重复项,则可以尝试以下方法:

List<Foo> foosUniqueByName = fooList.stream()
                .collect(Collectors.groupingBy(Foo::getName)) // group by name to
                .values().stream()                            // list of lists of foo
                .map(list -> list.get(0))                     // select the first foo
                .collect(Collectors.toList());                // get new list

推荐阅读