java - 删除其他 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();
也不是一个好主意。
我将不胜感激任何帮助!
解决方案
如果您只需要从fooList
by 特定属性中删除重复项,则可以尝试以下方法:
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
推荐阅读
- python - 如何为包含整数的列表提取字符串?
- python-3.x - 在 python 中使用套接字编程的网络嗅探原始格式
- r - 如何为在另一列中共享相同 ID 的列中的所有唯一元素创建列表?
- spss - 计算有条件的出现次数
- c# - 转换字符串时如何修复输入字符串错误
- icu - ICU 表达式 *select* 未检测到空值
- amazon-web-services - 如何在我的 AWS 控制台中查看我的 KCL 分片 ID?
- react-native - React Native:row-flexDir 中的文本在 iOS 上不显示(Android 有效)
- c# - 如何使用类重构 c# 代码阶段?
- oracle - 计算机编程中学生的姓名和分数