想要在使用 ForEach 时限制循环。

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

wanted to limit the looping while using ForEach

问题

从数据库获取了100条记录,我想循环10次并执行某些操作。
然后再循环并执行某些操作...直到读取完最后一条记录为止。

我看到的问题是

for (int number: numbers) {
    add(number);
    //添加10个项目后,我想完成一个函数并继续循环
}

但在Java中,如果使用上述循环,我们可以看到它会遍历完整个列表然后退出。

我知道在早期版本中,我们可以通过计数器进行迭代,类似于

for(int i=0; i<10;i++)  

像这样一些东西。

我的问题是,如果forEach循环不提供这种灵活性,那么为什么Sun Java引入了一个会完全迭代的循环机制呢?

试图理解这个设计的逻辑。

英文:

Say I got 100 records from DB, I want to loop 10 times and perform some action.
and loop again and perform some action.. it continues until the last record is read.

The problem what i am seeing is

for (int number: numbers) {
    add(number);
    //after adding 10 items I want to complete a function and continue the loop
}

But here in Java, if use the above loop we can see it will iterate the complete list and comes out.

I know in older versions, we can iterate by counter like

for(int i=0; i<10;i++)  

some thing like this.

My question is if forEach loop doesnot provide this flexibility, then why Sun Java introduced to a looping mechanism where it will iterate completely.

Trying to understand the logic of this design.

答案1

得分: 3

你可以在嵌套的条件下使用 forEach 或 for-in。

for (number: numbers) {
    if (number != (multOfTen)) {
        
        myFunction(number);
        add(number);
    
    } else {
    
        add(number);
    
    }
}

你需要用一个包含只有十的倍数的表达式替换 multOfTen。一个方法是使用正则表达式来检查最后一位数字是否为零(只要你使用整数)。

英文:

You can use a forEach or for-in with a nested conditional.

for(number: numbers){
     if(number != (multOfTen)){
        
         myFunction(number);
         add(number);
    
     }else{

          add(number);

     }
}

you will need to replace multOfTen w/ an expression that includes only multiples of ten.
One way to do this is to use regEx to check that the last digit is zero (so long as your using integers.)

答案2

得分: 2

按照名称,forEach 将在整个集合上进行迭代。这适用于 JavaScript 和其他几种语言。但是您可以根据条件中止/跳过迭代(这取决于语言实现细节)。

英文:

As the name suggests, forEach will iterate over the whole collection. This is the same for JavaScript and several other languages. However you can abort / skip the iteration with a condition (which depends on the language implementation details).

答案3

得分: 2

以下是翻译好的内容:

for循环和forEach循环之间的区别。Java之所以有这两个循环,是有原因的。forEach是增强型的for循环。根据需求,两者都有各自的用途。

for

这个我们可以用于一般情况。它完全基于索引。如果你想要操作特定索引处的数据,或者想要根据元素的索引执行一些操作,你应该使用for循环。

forEach

这仅适用于集合和数组。它一次遍历整个集合。这意味着在迭代过程中不能获得元素的索引。当您需要操作列表中的每个数据,而不管其索引如何时,可以使用它。例如,要打印给定列表中的所有元素,而不是编写传统的for循环:

for (int i = 0; i < list.length(); i++){
    System.out.println(list(i));
}

我们使用forEach循环:

list.forEach(e -> {
    System.out.println(e);
});

这种方式更易读、易用且简洁。

英文:

There are difference between for and forEach loop. There are reason why java has these 2. forEach is enhance for loop. Both have their usage based on requirements.

for

This we can use for general purpose. This is totally based on indexes. If you want to play with data at particular index or want to perform some actions based on index of element, you should use for.

forEach

this is used with only collections and arrays. This iterate over whole collections at once. Means you can't have index of element while iterating it. This is used when you manipulate each data in list regardless whats its index. For example to print all element in a given list, instead of writing classical for loop

for (int i =0; i &lt; list.length(); i++){

  System.out.println(list(i));

}

we use forEach loop

list.forEach(e -&gt; {
      System.out.println(e);
});

this is more readable, easy to use and crisp.

答案4

得分: 1

因为有时候你所提出的问题或者你正在使用 java 进行的实现并不需要数组的索引,只是简单地需要数组中的元素。

所以,你可以不必编写整个 for(int i=0;i<arr.length;i++) 的代码,而是可以直接使用 foreach,并且用一个简单的变量名代替 arr[i]

英文:

because sometimes the question or the implementation you're doing using java doesn't need the index of the array "simply".

so instead of writing the whole for(int i=0;i&lt;arr.length;i++) thing you can just use foreach and instead of arr[i] you use a simple variable name.

答案5

得分: 0

这实际上是可以使用相同的Stream API实现的,但超出了forEach的范围。如果局限于forEach,你想要做的是不可能的。forEach的目的是在可迭代或流的所有元素上执行某些操作,而不会产生偏见。你可以将对象分成每组10个,然后对于每个包含10个对象的分组,执行你想要的操作,即将所有对象添加到基础集合中,然后执行一些其他操作,这也是你想要的。

        List<Integer> values = IntStream.range(0, 100)
                .boxed()
                .collect(Collectors.toList());

        int batch = 10; 

        List<List<Integer>> groupsOfTen = IntStream.range(0, values.size() / batch + 1)
                .map(index -> index * batch)
                .mapToObj(index -> values.subList(index,
                        Math.min(index + batch, values.size())))
                .collect(Collectors.toList());
        
        groupsOfTen.forEach(myListOfTen -> myListOfTen.forEach(individual -> {
            
        }));
英文:

This is actually possible using the same Stream api but it's beyond the scope of forEach. What you want to do isn't possible by limiting yourself to forEach. The purpose of forEach is to execute some action without bias on all elements of an Iterable or Stream. What you can do is break down your objects into groups of 10 and then for each grouping of 10, do what you want which is add all to the underlying collection and then perform some other action which is what you want as well.

        List&lt;Integer&gt; values = IntStream.range(0, 100)
                .boxed()
                .collect(Collectors.toList());

        int batch = 10; 

        List&lt;List&lt;Integer&gt;&gt; groupsOfTen = IntStream.range(0, values.size() / batch + 1)
                .map(index -&gt; index * batch)
                .mapToObj(index -&gt; values.subList(index,
                        Math.min(index + batch, values.size())))
                .collect(Collectors.toList());
        
        groupsOfTen.forEach(myListOfTen -&gt; myListOfTen.forEach(individual -&gt; {
            
        }));

huangapple
  • 本文由 发表于 2020年7月27日 20:36:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63115493.html
匿名

发表评论

匿名网友

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

确定