-3

Below code snippet trying to add 100 users then prints in console . But I require for loop equivalent in Java 8 using Instream.range(1,100) ....

public class UsersMain {

    public static void main(String[] args)  {

     List<Users>  users =new ArrayList<>();
        for (int i=0;i<=100;i++) {
            users.add(new Users());
        }
  }
}

Users Class with Constructor:

public class Users  {
    public Users() {
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
sekhar
  • 105
  • 6
  • how about this :`List users = IntStream.rangeClosed(0, 100).mapToObj(i -> new Users()).collect(Collectors.toList());` – soorapadman Feb 13 '19 at 05:05

2 Answers2

2
  List<Users> users = IntStream.range(0, 100)
                     .mapToObj(i -> new Users()) 
                     .collect(Collectors.toList());

You can use any range() or rangeClosed() methods, the key difference between both are:

range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream.range(1,5) generates a stream of ‘1,2,3,4’ of type int.

rangeClosed() method generates a stream of numbers starting from start value and stops after generating the end value, i.e start value is inclusive and end value is also inclusive. Example: LongStream.rangeClosed(1,5) generates a stream of ‘1,2,3,4,5’ of type long.

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

You can use rangeClosed amd mapToObj as:

List<Users> users = IntStream.rangeClosed(0, 100) // rangeClosed for '<='
        .mapToObj(i -> new Users()) // would prefer at least an 'index' attribute to distinguish these objects
        .collect(Collectors.toList()); // collectin to a list

Note: Though the above code is same as your for loop, yet if you're trying to add 100 users specifically you must use range instead of rangeClosed.

Naman
  • 27,789
  • 26
  • 218
  • 353