-1

我想在 Java 中合并两个对象列表。一个是来自数据库的对象列表,第二个列表来自 Excel。

  1. 第一个对象列表包含以下数据: [name(str),valid_from(date),valid_to(date),active(flag)]
    如果名称、活动标志相等并且 obj1、obj2 - valid_from、valid_to 的日期是不相交的间隔,则对象相等。
    只有当活动标志不相等时,列表中才能有两个元素具有重叠的日期间隔和相同的名称。

  2. 第二个对象列表包含相同的数据以及关于是否在第一个列表上更新、删除或创建新记录的信息: [name(str),valid_from(date),valid_to(date),active(flag), action_type(c/u/d)]

//编辑:我的代码是:

public class ClassA {
    private String name;
    private Date validFrom;
    private Date validTo;
    private boolean active;

    public ClassA(String name, Date validFrom, Date validTo, boolean active) {
        this.name = name;
        this.validFrom = validFrom;
        this.validTo = validTo;
        this.active = active;
    }

    public String getName() {
        return name;
    }

    public Date getValidFrom() {
        return validFrom;
    }

    public Date getValidTo() {
        return validTo;
    }

    public boolean isActive() {
        return active;
    }

public static void main(String[] args) {
    List<ClassA> objectsFromDB = getObjectsFromDB();
    List<ClassB> objectsFromFile = getObjectsFromFile();

    Map<String, ClassA> objectNameToClassA = buildObjectNameToClassAMap(objectsFromDB);

    List<ClassA> objectsToCreate = new ArrayList<ClassA>();
    List<ClassA> objectsToUpdate = new ArrayList<ClassA>();
    List<ClassA> objectsToDelete = new ArrayList<ClassA>();

    for(ClassB object: objects) {
         ActionType actionType = object.getActionType();
         if(ActionType.CREATE.equals(actionType) {
             objectsToCreate.add(object.getObjectA());
         }
         if(ActionType.UPDATE.equals(actionType) {
             objectsToUpdate.add(object.getObjectA());
         }
         if(ActionType.DELETE.equals(actionType) {
             objectsToDelete.add(object.getObjectA());
         }
    }


}

    private static Map<String, ClassA> buildObjectNameToClassAMap(List<ClassA> objects) {
        Map<String, ClassA> result = new LinkedHashMap<String, ClassA>();
        for(ClassA object: objects) {
           result.put(object.getName(), object);
        }
        return result;
    }

}

enum ActionType {
    CREATE, UPDATE, DELETE;
}

class ClassB {
    private ClassA classA;
    private ActionType actionType;
    public ClassB(ClassA classA, ActionType actionType) {
        this.classA = classA;
        this.actionType = actionType;
    }

    public ClassA getClassA() {
         return classA;
    }

    public ActionType getActionType() {
        return actionType;
    }

}
4

1 回答 1

0

I would first define a class for your objects where you override the equals method in order to respect your conditions of equality. Then I would use one of the classes of java.util that implement the Set interface, HashSet for example. Then use the add method on this set with your objects. In set arithmetics, adding is a set union and so it performs a merge.

于 2013-01-24T16:14:28.450 回答