Java streams 9. Create numeric stream using range()

There are two versions of the range() method: 
— range(int startInclusive, int endExclusive)
— rangeClosed(int startInclusive, int endInclusive)
Their usage is pretty straightforward:

  
  IntStream intStream1 = IntStream.range(3, 7);
  intStream1.forEach(System.out::print);  //prints: 3456

  IntStream intStream2 = IntStream.rangeClosed(3, 7);
  intStream2.forEach(System.out::print);  //prints: 34567

  LongStream longStream1 = LongStream.range(3, 7);
  longStream1.forEach(System.out::print);  //prints: 3456
  
  LongStream longStream2 = LongStream.rangeClosed(3, 7);
  longStream2.forEach(System.out::print);  //prints: 34567
     

As you can see, these methods create streams that emit sequential values starting with startInclusive. The difference between the methods is that rangeClosed() creates a stream that also emits the endInclusive value.

In the next post, we will talk about creating a numeric stream using methods 
— Stream<String> Files.lines(Path path)
— Stream<String> Files.lines(Path path, Charset cs)
— Stream<Path> Files.list(Path dir)
— Stream<Path> walk(Path start, FileVisitOption… options)
— Stream<Path> walk(Path start, int maxDepth, FileVisitOption… options)

See other posts on Java 8 streams and posts on other topics.
You can also use navigation pages for Java stream related blogs:
— Java 8 streams blog titles
— Create stream
— Stream operations
— Stream operation collect()
The source code of all the code examples is here in GitHub

, ,

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes