How to use IntStream in lambdas and method references in Java?

Java 8Object Oriented ProgrammingProgramming

An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.

Syntax

public interface IntStream extends BaseStream<Integer, IntStream>

Example

import java.util.stream.IntStream;

public class StringToIntegerStreamTest {
   public static void main(String[] args) {
      String str = "Tutorials Point";
      IntStream stream = str.chars();
      stream.forEach(element -> System.out.println(((char)element))); // using
lambda expression
   }
}

Output

T
u
t
o
r
i
a
l
s

P
o
i
n
t


Example

import java.util.*;
import java.util.stream.IntStream;

public class IntStreamTest {
   public static void main(String[] args) {
      final List<Integer> list = Arrays.asList(1, 2, 3);
      list.stream().forEach(System.out::println);  // Using method reference

      final IntStream intStream = IntStream.iterate(1, i -> i + 1);
      final int sum = intStream.limit(100).sum();
      System.out.println("sum: " + sum);
   }
}

Output

1
2
3
sum: 5050
raja
Published on 03-Jan-2020 12:40:24
Advertisements