sagar_challa
sagar_challa

Reputation: 13

Iterator to return list

I am trying to implement this with the help of enhanced for loop, but my question is if I use the iterator for the example below how do I make sure that my return type is picking up the corresponding value of "XYZ"?

List<Apples> a1 = new List<Apples>();
if(a1.iterator().next().equals("XYZ")
{
   return a1.iterator().next().getFruits();
}

Upvotes: 1

Views: 95

Answers (2)

shippi
shippi

Reputation: 2454

Probably you want to implement the following

List<Apples> apples = new List<Apples>();
for(Apple a : apples) {
 if("xyz".equals(a.getSomethingWhatReturnsString())) return a.getFruits();
}

Upvotes: 2

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Why use an iterator here? a simple get() will do the trick:

if (a1.get(0).equals("XYZ")) {
    return a1.get(0).getFruits();
}

Of course, if you intend to traverse all the elements in a list then you're missing a for here. And besides, your code won't work: it's a list of apples, you can't compare an apple with a string! Perhaps you meant something like this, replace getStringAttribute() with the appropriate attribute that you intend to compare with "XYZ":

for (Apple a : a1) {
    if ("XYZ".equals(a.getStringAttribute())) {
        return a.getFruits();
    }
}

Upvotes: 1

Related Questions