Search code examples
javalambdajava-stream

Compare two different java collection objects with a common attribute using java streams api


I have two Sets containing 2 different objects

1. Set<A> 
2. Set<B>
    class A {
       private String id;
       private String name;
       private B objB;
    }
    
    class B {
       private String id;
       private String email;
    }

I want to check if any object of A in the first Set has the same "id" in the second Set B.

If it b.getId().contains(a.getId), then that B object will be set in A object.

objA.setB(objB);

Based on a Predicate how can we store B object into A based on matching "id" attribute value (using Java streams)?


Solution

  • First arrange all the id values from the B objects into a Map for fast access. Then loop the A objects, looking up each A object’s id for a match in the map.

    Map<String,B> mapB = new HashMap<>();
    for (B element : setB) {
        mapB.put(element.id, element);
    }
    setA.forEach (
        a ->{
            B b = mapB.get(a.getId());
            if(b!=null){
                a.setB(b);
            }
        }
    );