0

Let's say I've got this two ArrayLists, the first one is of the type ObjectA, the second ObjectB.

These are ObjectA's variables:

 int id;
 double value;

And these are ObjectB's variables:

 int objAId;
 double disccountValue;

How can I retrieve the disccountValue of ObjectB where objAId is the same of the item on the first list? Just like in a SQL query, but in ArrayLists.

4
  • Possible duplicate of Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java Commented Feb 15, 2016 at 18:15
  • You can override the equals method, and get the object index that contains the value. ifContains() and indexOf() Commented Feb 15, 2016 at 18:19
  • One solution is to do a linear search in listA based on a given objAId from an ObjectB. If you sort listA by the id value, you can improve the speed by doing a binary search instead. Commented Feb 15, 2016 at 19:55
  • Similarly if you want to search for something in listB, you can do either a linear or binary search depending on whether you sort the list before searching. Commented Feb 15, 2016 at 19:57

1 Answer 1

0

If you're trying to get the value for each object A:

for(ObjectA objA : arrayListOfObjectAs){
    int id = objA.id;
    for(ObjectB objB : arrayListOfObjectBs){
        if(id == objB.objAId){
            //do what you want with the objB.discountValue here
        break;
        }
    }
}

If you're only looking for a single id you can get rid of that outer for loop

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.