You are trying to do what Java is not really intended for.
If you are able to do this, you would be better off adding the Object1 attribute , which would be a list of Object2 containing the objects associated with this .
If you cannot, we have the opportunity to do it naively, otherwise you can try something like this:
HashSet<Integer> hs = new HashSet<Integer>(list2.size()); for(Object2 o : list2) { hs.add(o.object1id); } //hs contains all the ids of list2 List<Object1> result = new ArrayList<Object1>(); //Or another class implementing List for(Object1 o : list1) { if(hs.contains(o.id)) result.add(o); }
Not really, since you should store all identifiers as a HashSet, but since adding and accessing elements in a HashSet are O (1) (theoretically), the O (N + M) algorithm
If the Object3 class is built with Object1 and Object2 , use HasMap instead of HashSet , where the keys are identifiers and the values โโare Object2. The last for loop in the code will look like this:
Object2 o2 = hs.get(o.id); if(o2 != null) result.add(new Object3(o, o2);
In addition to Oscar Lopez's comment:
If your objectid1 is not unique, you need to adapt the code as follows:
HashMap<Integer, List<Object2>> hm = new HashMap<Integer, List<Object2>>(); for(Object2 o : list2) { List<Object2> l = hm.get(o.objectid1); if(l != null) { l.add(o); } else { List<Object2> l = new ArrayList<Object2>(); l.add(o); hm.put(o.objectid1, l); } //hm is map, where each entry contains the list of Object2 associated with objectid1 List<Object1> result = new ArrayList<Object1>(); for(Object1 o : list1) { List<Object2> l = hm.get(o.id); //l contains all Object2 with object1id = o.id for(Object2 o2 : l) result.add(new Object3(o, o2)); }
Still in O (n + m), but with big constants ...