Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two Lists in Java

Tags:

java

list

I need to join two Lists in Java. I've a list which has a VO that has a name and description. I've another list which has same VO type that has name and Address. The "name" is same. I need to create a List with this VO which has both name, address and description. The VO structure is

public class PersonDetails{
    private String name;
    private String description;
    private String address;
//getters and setters
}

Can someone please suggest me the best way to implement it?

like image 417
Apps Avatar asked Nov 20 '25 16:11

Apps


1 Answers

It depends:

If the lists contain both exactly the same data, you can sort them both by name, iterate over them en set the missing property.

If not, I would put the first list in a Map, with the name as key. Then iterate over the second list, look in the map for the VO and set the value. After that, just get all the value's out of the map again as a List.

public List<Vo> merge(List<Vo> list1, List<Vo> list2) {

    Map<String, Vo> tempMap = new HashMap<String, Vo>();

    for (Vo v : list1) {
        tempMap.put(v.name, v);
    }

    for (Vo vv : list2) {

        //The if is in case the 2 lists aren't filled with the same objects            
        if (tempMap.containsKey(vv.name)) {
            tempMap.get(vv.name).description = vv.description;
        } else {
            tempMap.put(vv.name, vv);
        }
    }

    return new ArrayList<Vo>(tempMap.values());

}

If the lists contain both EXACT the same VO (equal by name), you can use this.

public List<Vo> merge(List<Vo> list1, List<Vo> list2) {

    Collections.sort(list1, new Comparator<Vo>() {

        public int compare(Vo o1, Vo o2) {
            return o1.name.compareTo(o2.name);
        }
    });

    Collections.sort(list2, new Comparator<Vo>() {

        public int compare(Vo o1, Vo o2) {
            return o1.name.compareTo(o2.name);
        }
    });

    for(int i = 0; i < list1.size(); i++){
        list1.get(i).description = list2.get(i).description;
    }

    return list1;

}
like image 82
Cid54 Avatar answered Nov 23 '25 05:11

Cid54