简体   繁体   中英

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();
}

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();
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM