June 29, 2022

Java Primitive Type Streams With Examples

Java Stream API was one of the important addition in Java 8 and provides a very efficient way to process collection of objects. Since Stream only works with object references so using it with primitive types is not very efficient. You will need to use wrapper classes to wrap the primitive data types when used with Stream i.e. Stream<Integer>, Stream<Long>, Stream<Double> making it inefficient because of conversion of primitive types to corresponding objects.

Fortunately Java Stream API provides primitive specializations of Stream for the primitive types int, long and double. The primitive type streams available in Java are-

  • IntStream- This is the int primitive specialization of Stream.
  • LongStream- long primitive specialization of Stream.
  • DoubleStream- This is the double primitive specialization of Stream.

Creating primitive Streams in Java

To create a primitive stream all the three classes (IntStream, LongStream, DoubleStream) provide empty() and of() methods.

There is also a range() method which is provided in IntStream and LongStream classes in Java Stream API.

empty() method

empty()- This static method returns an empty sequential primitive stream.

To create an empty IntStream-

IntStream intStream = IntStream.empty();

To create an empty LongStream-

LongStream longStream = LongStream.empty();

of() method

There are two overloaded of() methods, for IntStream these of() methods are defined as-

  • static IntStream of(int t)- Returns a sequential IntStream containing a single element.
  • static IntStream of(int... values)- Returns a sequential ordered stream whose elements are the specified values.

Same way LongStream and DoubleStream have of() methods taking long and double as arguments.

Here is an example where max element in the DoubleStream is returned, DoubleStream is created using of() method.

double max = DoubleStream.of(6.7, 8.9, 14.56, 22.34, 55).max().getAsDouble();
System.out.println("Max value- " + max);
Output
Max value- 55.0

range() and rangeClosed() methods

For IntStream and LongStream range() and rangeClosed() methods are also there to create streams.

  • range(int startInclusive, int endExclusive)- Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
  • rangeClosed(int startInclusive, int endInclusive)- Returns a sequential ordered IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.

To create an int stream of integers 1-9 using range() method.

IntStream.range(1, 10).forEach(System.out::println);
Output
1
2
3
4
5
6
7
8
9

To create an int stream of integers 1-5 using rangeClosed() method.

IntStream.rangeClosed(1, 5).forEach(System.out::println);
Output
1
2
3
4
5

Using Arrays.stream() methods

By passing an int array, long array or double array as an argument in Arrays.stream() method you can get a corresponding primitive type stream. There is also an overloaded variant of this method where range can be specified for the array index.

  • stream(int[] array, int startInclusive, int endExclusive)

    Here

    startInclusive- the first index to cover, inclusive

    endExclusive- index immediately past the last index to cover

For example to get a DoubleStream from a double array from index 1-3.

double[] dArray = new double[] {4, 5.6, 7.89, 0.34, 12};
Arrays.stream(dArray, 1, 4).forEach(System.out::println);
Output
5.6
7.89
0.34

Operations in Java primitive streams

Most of the frequently used arithmetic operations like count, average, sum, max, min are provided for these primitive streams in Java.

1. To get sum of all the elements in a double array using a DoubleStream.

double[] dArray = new double[] {4, 5.6, 7.89, 0.34, 12};
double sum = Arrays.stream(dArray).sum();
System.out.println("Sum of array elements- " + sum);
Output
Sum of array elements- 29.83

2. To get the maximum element in a DoubleStream.

double max = DoubleStream.of(6.7, 8.9, 14.56, 22.34, 55).max().getAsDouble();
System.out.println("Max value- " + max);
Output
Max value- 55.0

3. To get the maximum element in a DoubleStream.

int min = IntStream.of(6, 8, 14, 22, 55).min().getAsInt();
System.out.println("Min value- " + min);
Output
Min value- 6

4. To get average of values in a IntStream.

double average = IntStream.of(6, 8, 14, 22, 55).average().getAsDouble();
System.out.println("average of values- " + average);
Output
average of values- 21.0

Converting Stream to primitive stream

To convert a Stream of objects to stream of primitive types there are mapToInt, mapToLong and mapToDouble methods in Stream interface.

MapToInt method example

Let’s say there is an Employee class with name, dept, age fields. You need to find out the max age in the list of employees.

public class Employee {
  private String name;
  private String dept;
  private int age;

  Employee(String name, String dept, int age){
    this.name = name;
    this.dept = dept;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}

Using mapToInt method you can get an IntStream having only the age field and then get the max age.

List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("Jack", "Finance", 55));
employeeList.add(new Employee("Lisa", "Accounts", 34));
employeeList.add(new Employee("Nikita", "IT", 28));
employeeList.add(new Employee("Tony", "HR", 42));
int maxAge = employeeList.stream().mapToInt(e -> e.getAge()).max().getAsInt();
System.out.println("Max age- " + maxAge);
Output
Max age- 55

Converting primitive stream to Stream of objects

There are scenarios when you would want to convert stream of primitive type to its wrapper equivalent stream for that boxed method in Java Stream API is used.

For example if you want to collect an IntStream to a List you need to box int values to corresponding Wrapper class and then collect it.

List<Integer> intList = IntStream.of(6, 8, 14, 22, 55).boxed().collect(Collectors.toList());
System.out.println("List- " + intList);
Output
List- [6, 8, 14, 22, 55]

That's all for the topic Java Primitive Type Streams With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment