Java Tutorial - 11 Stream

Introduction

In Java programming language, the collection type like List can be manipulated using Stream.

Optional Data Type

When using Stream, there is a data type called Optional. Optional data type means a data that allows null value. Some Stream functions use Optional as the return value.

When there is a function that returns Optional data type. The result must be checked using isPresent() function to ensure the value is exists or not null.

Using Java Stream

To use Stream in Java, import the Stream package.

import java.util.stream.*;

Then, convert the collection into Stream using stream() function.

// Basic syntax
collection_name.stream()

map function

The map function is used to create a mapping mechanism into the collection.
In this example, every data inside collection is multiplied by 2.

List<Integer> numbers = new ArrayList<>();

numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);

// using map function
List<Integer> updatedNumbers = numbers
                .stream()
                .map((i) -> i * 2)
                .collect(Collectors.toList());

System.out.println(updatedNumbers);

Output

[2, 4, 6, 8]

Based on the code above, the lambda function (anonymous function) is added inside the map() function to multiply every data inside the collection by 2. The lambda that defined inside the map() function is (i) -> i * 2. Then, the result from map() function returns Stream that can be collected into the list by using collect(Collectors.toList()) function.

sum function

The sum function is useful to calculate the sum of the values inside the collection. This function is suitable for the collection that contains numeric values.

In this example, the sum is used in numbers collection.

The numbers collection is defined in map section.

// using sum function
int sum = numbers.stream().mapToInt(i -> i).sum();
System.out.println(sum);

Output

10

Based on the code above, the sum result's data type is returned based on the collection type. Because the numbers collection type is a integer collection. The sum result's data type is integer.

average function

The average function is used to calculate the average of the values inside the collection. This function is suitable for the collection that contains numeric values.

In this example, the average is used in numbers collection.

// using average method
OptionalDouble average = numbers.stream().mapToInt(i -> i).average();
// check if the value is exists
if (average.isPresent()) {
    System.out.println(average.getAsDouble());
}

Output

2.5

Based on the code above, the average result returns Optional data type. To check if the value is exists, use the isPresent() function then the value can be accessed safely.

max and min function

The max function is used to find the maximum value. The min function is used to find the minimum value.

In this example, these functions is used in numbers collection.

Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder());
Optional<Integer> min = numbers.stream().min(Comparator.naturalOrder());

if (max.isPresent() && min.isPresent()) {
    System.out.println("maximum value: " + max.get());
    System.out.println("minimum value: " + min.get());
}

Output

maximum value: 4
minimum value: 1

Based on the code above, the maximum and minimum value is returned. Because both of these functions return Optional data type, the isPresent() function is used. The Comparator.naturalOrder() is used inside max() and min() function to define the default comparator.

filter function

The filter function is used to select some values based on the specific criteria or condition.

In this example, the filter function is used to select only even values in numbers collection.

// using filter to filter only even values
List<Integer> integers = numbers
                .stream()
                .filter(integer -> integer % 2 == 0)
                .collect(Collectors.toList());
System.out.println(integers);

Output

[2, 4]

Based on the code above, the return value from filter() function is a Stream that the values can be collected using collect(Collectors.toList()). The result from filter() function contains even value only.

allMatch function

The allMatch function is used to check if all values inside collection meets the certain criteria or condition.

In this example, the allMatch is used to check if all values inside numbers collection is even.

// using allMatch to check if all values is even
boolean allMatch = numbers.stream().allMatch(integer -> integer % 2 == 0);
System.out.println(allMatch);

Output

false

Based on the code above, the numbers collection ([1,2,3,4]) has even values but the other values is not so the false is returned.

anyMatch function

The anyMatch function is used to check if a certain value meets certain criteria or condition.

In this example, the anyMatch is used to check if a certain value is even in numbers collection.

// using anyMatch to check if a certain value is even
boolean anyMatch = numbers.stream()
               .anyMatch(integer -> integer % 2 == 0);
System.out.println(anyMatch);

Output

true

Based on the code above, there is a even value insied numbers collection so the true is returned.

sorted function

The sorted function is used to sort a values inside collection. By default, the sorted function is sorting the value from smallest to largest value.

In this example, the sorted function is used to sort a value inside myNums collection.

List<Integer> myNums = new ArrayList<>();
myNums.add(44);
myNums.add(24);
myNums.add(1);
myNums.add(19);

// using sorted to sort the collection
List<Integer> sortedNums = myNums.stream().sorted().collect(Collectors.toList());
System.out.println("Sorted list: " + sortedNums);

Output

Sorted list: [1, 19, 24, 44]

Based on the code above, the value is sorted from the smallest value into largest value.

Notes

  • Use the Stream functions based on the use cases.
  • When a Stream function returns Optional data type, check the value existence using isPresent() to ensure the value is exists or not null.

This is the final part of java basic tutorial series in this blog. I hope this java basic tutorial series is helpful for learning the Java programming language 😀.

Sources

  • Learn more about Java Stream in this link.

I hope this article is helpful for learning the Java programming language. If you have any thoughts or comments you can write in the discussion section below.

23