我有一个列表,我需要在其中遍历列表并找到匹配项,以便将它们组合起来并将它们添加到另一个列表中。问题是我一直遇到多次迭代某些元素或跳过某些元素的问题。
列表中的每个对象都有两个 int 值。如果第一个 int 值是两个元素之间的匹配项,我需要组合两个对象的第二个 int 值并将该对象添加到另一个列表
如果我有一个列表 ((12,10), (13,10), (12,5), (14,5), (14,10), (10,20))
我想将 12 位和 14 位合并到一个新列表中
((12,15), (14,15))
我的原始列表将留下 ((13,10), (10,20))
我试过在有和没有迭代器的情况下使用 for 循环,但没有成功。
List<Record> finalList = new ArrayList<Record>();
for (int i = 0; i < tempAggregateList.size(); i++){
Record record = tempAggregateList.get(i);
for (int j = i+1; j < tempAggregateList.size(); j++){
Record nextRecord = tempAggregateList.get(j);
if (record.getFirstValue() == nextRecord.getFirstValue()){
record.setSecondValue(record.getSecondValue() + nextRecord.getSecondValue());
//then remove nextRecord from tempAggregateList
}
}
finalList.add(record);
}
我现在的方式是,我的第一个 for 循环将遍历我已经组合并添加到 finalList
的元素。最简单的方法是删除我添加到 finalList 的元素,但我还没有找到办法。
最佳答案
您应该能够使用流:
// group by first value
Map<Integer, Record> newList = list.stream().collect(Collectors.groupingBy(Record::getFirstValue,
// for each record list for the same first value, add the second one
Collectors.collectingAndThen(
// add first and second value for each pair
Collectors.reducing((r1, r2) -> new Record(r1.getFirstValue(), r1.getSecondValue() + r2.getSecondValue())),
// there will be no empty list, so all optionals will be present
Optional::get));
现在你有一个 Map<Integer, Record>
键是第一个值,键是组合 Record
.
编辑:我意识到这可以更容易地完成
BinaryOperator<Record> addRecords = (r1, r2) -> new Record(r1.getFirstValue(), r1.getSecondValue() + r2.getSecondValue());
Map<Integer, Record> map = list.stream().collect(
toMap(Record::getFirstValue, r -> r, addRecords));
如果您想要一个列表并在一行中执行此操作
List<Record> result = list.stream().collect(
collectingAndThen(
toMap(Record::getFirstValue, r -> r, addRecords),
m -> new ArrayList<>(m.values())));
从 Collectors
静态导入是隐含的。
关于java - 在一个列表中查找匹配项并将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53597349/