Home > front end >  How do i create a foreach loop using java
How do i create a foreach loop using java

Time:10-11

I'm trying to build a List for each and i don't know what to do so. what i'm trying to do is create a list.add() but i wanna have a min year to max year so like start at 1980 to 2014 but i don't wanna have to create all the list so i'm trying find help with doing it with a foreach loop.

CodePudding user response:

you can do the loop with a array then use foreach loop for each element in the array. hope this help you

CodePudding user response:

I believe what you are saying is that you are trying to create a list with values from x to y so in your case, 1980 to 2014. And you don't want to have to individually add each one, i.e.

list.add(1980);
list.add(1981);
list.add(1982);
...

What you can do is create an IntStream for a range of values and then add all of them to the list.

Like this,

List<Integer> years = IntStream.rangeClosed(1980, 2014).boxed().toList();

Note: IntStream.rangeClosed(x, y) will be inclusive to upper and lower bounds, meaning it will include all values from x to y, including x and y.

  •  Tags:  
  • java
  • Related