for (final A a : listOfAs.getList()) {
do something (if statement), not using a
}
Is there any way to improve this code in Java 8? I.e. I want to perform something as many times as how many elements are in the list, but I will not use the element a inside the loop. For example, python has
for _ in range(n):
Is there something similar in Java 8?
Thank you.
Example Java 8 code showing how to use range () and rangeClosed () methods The main () method of RangeNRangeClosedExample class, first starts with examples of IntStream.range () and IntStream.rangeClosed () methods. The stream elements generated are then printed using Stream.forEach () statement.
We can use a traditional for loop to generate numbers in a specified range: The code above will generate a list containing numbers from start (inclusive) to end (exclusive). 2.2. JDK 8 IntStream.range IntStream, introduced in JDK 8, can be used to generate numbers in a given range, alleviating the need for a for loop:
Java List List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also.
Syntax of Range in Java 1 Syntax of IntStream range#N#static IntStream range (int startInclusive, int endExclusive)#N#Parameters:#N#IntStream: This... 2 Syntax of LongStream range More ...
You can use IntStream.range :
IntStream.range(0,listOfAs.getList().size()).forEach(i->{...});
This won't iterate over your list.
The forEach
method of IntStream
accepts an IntConsumer
, which is a functional interface that has the method void accept(int value)
. In my example I supplied a lambda expression that matches that interface. You do get the int
index, whether you use it or not.
you can use the famous for
loop:
for(int i = 0; i < listOfAs.getList().size(); i++){
}
This will not iterate through the elements of your list.
You can use Streams :
listOfAs.stream().forEach(Consumer c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With