简体   繁体   中英

Accessing outer loop variable from inside loop in Java

My list consist of list character definition like List<Character> listCharacter = new ArrayList<Character>();

Character class:

private List<Result> results;

Result Class:

 private int id;

 private String name;

I am trying to iterate over listCharacter like

listCharacter.forEach((characters) -> {

            characters.getResults().forEach((result) -> {

                if (result.getId() == id) {
                    return result;
                }

            });
        });

But when am trying this i got foreach not applicable the type Iterable is not applicable for the arguments (( result) -> {}) error. I know chain loop not possible with foreach loop.

Also i know we can use consumers like duplicate question solutions.But then i can't reach outer loop variable inside inner loop.The Consumer classes just using it and disposing it.Therefore I don't wanna use that.

How can i do this i mean reaching outer loop variable inside inner loop without dealing with this such errors?

TLDR: I have 2 list objects. I am iterating over outer one(listCharacter) that who has inner one list object(result) which has id and name.If the id matched the method would return.That's all.

I would firstly suggest that you avoid calling a custom class Character as that's already in use by the Java API. you don't have to but it would avoid confusion here and there. Consider remaining to something more meaningful and reflecting of what the class does.

Also note that you cannot return a result from forEach .

You can accomplish your intended result as follows:

source.stream()
      .map(Character::getResults)
      .flatMap(Collection::stream)
      .filter(s -> s.getId() == id)
      .findFirst().orElse(null);

"results" is not a list or any other iterator, it's just a single object of type "Result". Thus, you can not iterate over it at all. Make sure getResults() actually returns a list, rather than a single object, and then you can iterate over it.

(Also note that forEach() is not actually a loop. It's a function call with a lambda function as a parameter. And as mentioned before, you can not use forEach() to collect some kind of result from the lambda function, you'll have to use map() for that.)

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