在Java中从内部循环访问外部循环变量

huangapple go评论95阅读模式
英文:

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<Result> is not applicable for the arguments ((<no type> 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 of it. Therefore, I don't wanna use that.

How can I do this, I mean reaching the outer loop variable inside the inner loop without dealing with these errors?

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

My list consist of list character definition like List&lt;Character&gt; listCharacter = new ArrayList&lt;Character&gt;();

Character class:

private List&lt;Result&gt; results;

Result Class :

 private int id;

 private String name;

I am trying to iterate over listCharacter like

listCharacter.forEach((characters) -&gt; {

			characters.getResults().forEach((result) -&gt; {
				
				if (result.getId() == id) {
					return result;
				}

			});
		});

But when am trying this i got foreach not applicable the type Iterable<Result> is not applicable for the arguments ((<no type> 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.

答案1

得分: 3

我首先建议您避免将自定义类命名为Character,因为这在Java API中已经被使用。您不一定要这样做,但这样可以避免造成混淆。考虑将类名命名为更有意义且能够反映类功能的名称。

此外,请注意您不能从forEach中返回结果。

您可以按照以下方式实现您的预期结果:

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

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 -&gt; s.getId() == id)
      .findFirst().orElse(null);

答案2

得分: 0

"results"不是一个列表或任何其他迭代器,它只是一个名为"Result"的单一对象。因此,您无法对其进行迭代。请确保getResults()实际上返回一个列表,而不是单个对象,然后您可以对其进行迭代。

(另请注意,forEach()实际上不是一个循环。它是一个带有lambda函数作为参数的函数调用。正如之前提到的,您不能使用forEach()从lambda函数中收集某种结果,您将需要使用map()来实现。)

英文:

"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.)

huangapple
  • 本文由 发表于 2020年5月29日 05:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/62074771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定