我有一个具有多个字段的程序集类。
我需要根据程序集代码从程序集对象列表中删除程序集类的重复对象,但在删除之前,我需要将程序集数量添加到匹配的程序集对象的数量中。
package com.company;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Assembly> assemblies = new ArrayList<>();
assemblies.add(new Assembly("abc1", 3.0));
assemblies.add(new Assembly("abc2", 6.0));
assemblies.add(new Assembly("abc3", 8.4));
assemblies.add(new Assembly("abc4", 9.0));
assemblies.add(new Assembly("abc1", 4.2));
assemblies.add(new Assembly("abc1", 6.3));
System.out.println("List with duplicates: "+assemblies);
HashSet<String> assmCode=new HashSet<>();
assemblies.removeIf(e->!assmCode.add(e.getAssemblyCode())); //remove the last two abc1
//but i need to add 4.2, 6.3 to 3.0 before removing
System.out.println("List without duplicates: "+assemblies);
}
}
class Assembly{
private String assemblyCode;
private double assemblyQty;
//There will be more such fields
public Assembly(String assemblyCode, double assemblyQty) {
this.assemblyCode = assemblyCode;
this.assemblyQty = assemblyQty;
}
public String getAssemblyCode() {
return assemblyCode;
}
请让我知道我是否可以在删除重复对象之前执行此类操作。我对 java 的集合 api 很陌生,很抱歉问这个问题解决方案是否简单。
只是为了澄清一下,输出必须是这样的:
包含重复项的列表: [Assembly{assembleCode='abc1', assemblyQty=3.0}, Assembly{ assemblyCode='abc2', assemblyQty=6.0}, Assembly{ assemblyCode='abc3', assemblyQty=8.4}, Assembly{ assemblyCode='abc4 ', assemblyQty=9.0}, Assembly{ assemblyCode='abc1', assemblyQty=4.2}, Assembly{ assemblyCode='abc1', assemblyQty=6.3}]
没有重复项的列表:[Assembly{assembleCode='abc1', assemblyQty=13.5}, Assembly{ assemblyCode='abc2', assemblyQty=6.0}, Assembly{ assemblyCode='abc3', assemblyQty=8.4}, Assembly{ assemblyCode='abc4 ', 装配数量=9.0}]
扬帆大鱼
相关分类