Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 range() of list?

Tags:

java

java-8

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.

like image 940
Tad Avatar asked Aug 26 '14 16:08

Tad


People also ask

How to use range () and rangeclosed () methods in Java 8?

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.

How to generate numbers in a specified range in Java?

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:

What is list list in Java?

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.

What is the syntax of range in Java?

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


3 Answers

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.

like image 149
Eran Avatar answered Oct 17 '22 22:10

Eran


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.

like image 27
eldjon Avatar answered Oct 17 '22 21:10

eldjon


You can use Streams :

listOfAs.stream().forEach(Consumer c);
like image 1
Arnaud Denoyelle Avatar answered Oct 17 '22 20:10

Arnaud Denoyelle