Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging one object into another object [duplicate]

Tags:

java

I have two Objects of same type.I want to create a method which can merge the properties of two object and can return a single object.

For Example: Consider a class ABC having 4 fields

Class ABC{
String name;
String id;
String salary;
String status;
}

Suppose the first object is

ABC[name=ZEE,id=2,salary=null,status=1]

and the second object is

ABC[name=john,id=null,salary=12200,status=null]

I want to make a generic method which can merge these two objects and can give result output as:

ABC[name=ZEE,id=2,salary=12200,status=1]

The method Should take two parameters of Object type:

Object  mergeObject(Object Obj1, Object Obj2){
}

Note: It will take the first object property if both the objects have non-null value for that property.

like image 454
Deepak Kumar Avatar asked Jun 11 '15 13:06

Deepak Kumar


People also ask

How do you combine two objects?

If you want to merge the second object into the first object, instead of creating a new object, you can use Object. assign() . The Object. assign(target, source) function merges the source into the target.

How do you merge duplicate values in an array of objects?

To merge duplicate objects in array of objects with JavaScript, we can use the array map method. to merge the items with the label value together. To do this, we get an array of labels without the duplicates with [... new Set(data.

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.

How do I merge two arrays in TypeScript without duplicates?

Example 1: Using concat() and for Loop In the above program, the two array elements are merged together and the duplicate elements are removed. Here, The two arrays are merged using the concat() method. The for...of loop is used to loop through all the elements of arr .


2 Answers

You're going to have to go the reflection route. I'm assuming you have a default constructor, otherwise the following won't work. Also, it needs two same types. It won't copy inherited fields, for that, you also need to add some code from here.

@SuppressWarnings("unchecked")
public static <T> T mergeObjects(T first, T second) throws IllegalAccessException, InstantiationException {
    Class<?> clazz = first.getClass();
    Field[] fields = clazz.getDeclaredFields();
    Object returnValue = clazz.newInstance();
    for (Field field : fields) {
        field.setAccessible(true);
        Object value1 = field.get(first);
        Object value2 = field.get(second);
        Object value = (value1 != null) ? value1 : value2;
        field.set(returnValue, value);
    }
    return (T) returnValue;
}

Here's an example

public static class ABC {
    private int id;
    private String name;
    private int[] numbers;

    public ABC() {
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int[] getNumbers() {
        return numbers;
    }

    public void setNumbers(int[] numbers) {
        this.numbers = numbers;
    }
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    ABC abc = new ABC();
    abc.setId(1);
    abc.setName("Hello");
    int[] newnumbers = new int[5];
    for(int i = 0; i < newnumbers.length; i++) {
        newnumbers[i] = i;
    }
    abc.setNumbers(newnumbers);
    ABC abc2 = new ABC();
    abc2.setName("World");

    ABC abcFinal = mergeObjects(abc, abc2);
    System.out.println("Properties of ABC Final:");
    System.out.println("ID: " + abcFinal.getId());
    System.out.println("Name: " + abcFinal.getName());
    System.out.println("Numbers: " + Arrays.toString(abcFinal.getNumbers()));
}

Output:

Properties of ABC Final:
ID: 1
Name: Hello
Numbers: [0, 1, 2, 3, 4]
like image 146
EpicPandaForce Avatar answered Nov 15 '22 01:11

EpicPandaForce


In case you want to create a new Object use:

public ABC mergeABC(ABC obj1, ABC obj2){
    ABC retVal = new ABC();
    retVal.name   = ((obj1.name   != null) ? obj1.name   : obj2.name   );
    retVal.id     = ((obj1.id     != null) ? obj1.id     : obj2.id     );
    retVal.salary = ((obj1.salary != null) ? obj1.salary : obj2.salary );
    retVal.status = ((obj1.status != null) ? obj1.status : obj2.status );
    return retVal;
}

If you want to "reuse" obj1 or obj2, simply use this as return value.

like image 38
dosw Avatar answered Nov 15 '22 01:11

dosw