a13e
a13e

Reputation: 928

Comparing fields of object store in arraylist using iterator

I am passing an integer value address to this function. This integer value is contained by one of the object stored in Arraylist "instrHolder". Now I want to first find out which object contains this value and return the entire object of type "Instruction". Here is what I am trying -

private static Instruction getInstruction( int address) {
    Iterator<Instruction> iterator = instrHolder.iterator();
    while(iterator.hasNext()){
        if(/*condition need to know*/)
        return /*need to know*/;
    }
}

How should I write the if condition and what should be my return statement? Please help me out?

Upvotes: 1

Views: 85

Answers (3)

Spotted
Spotted

Reputation: 4091

Since instrHolder is an ArrayList, don't bother with an Iterator. Rather use Stream and Optional. Also, in your code the behavior is not specified in case no element matches the address. In the code below it throws an exception, but it can also return a default value (with orElse()).

private static Instruction getInstruction( int address) {
    return instrHolder.stream()
                      .filter(i -> i.getAddress() == address)
                      .findFirst()
                      .orElseThrow(NoSuchElementException::new);
}

Upvotes: 1

Eran
Eran

Reputation: 393936

iterator.next() will give you the current instance of the List. You should check your condition on that instance and return it if the condition is satisfied :

private static Instruction getInstruction(int address) {
    Iterator<Instruction> iterator = instrHolder.iterator();
    while (iterator.hasNext()) {
        Instruction current = iterator.next();
        if (current.getSomeProperty().equals(someValue))
            return current;
    }
    return null;
}

As hinted by Spotted, you should decide what to return if no element of your list matches the condition. I chose to return null in this case.

Upvotes: 4

Vasu
Vasu

Reputation: 22442

You can use iterator.next() and because you wanted to compare integer address, you can refer below code:

while (iterator.hasNext()) {
            Instruction instruction = iterator.next();//Get single instruction
            //Get getAddress() from instruction object
            if (instruction.getAddressValue() == address) {
                return instruction;
            }
        }

Upvotes: 2

Related Questions