Java. The StreamAPI interface. Final methods

The StreamAPI interface. Final methods. Examples of using. Methods collect(), count(), forEach(), max(), min(), reduce(), toArray()


Contents


Search other sites:




1. Method collect(). The accumulation of items in the container. Example

The collect() method is used to collect items from the original stream in a changing container. The container can be, for example, a list, a set, and the like. The collect() method is called an operation of variable reduction.

The general form of the method is as follows:

<R, A> R collect(Collector<? super T, A, R> collector)

here

  • R – the type of the resulting container;
  • T – the type of elements in the original (calling) data stream;
  • A – internal storage type;
  • collector – an accumulation function represented by a lambda expression. The function determines the order of the accumulation process.

The collect() method refers to terminal operation.

Example. In the example, for a stream of numbers of type Double, the following accumulations of elements are demonstrated:

  • extract a set of type set<Double> from the data stream. To do this, use the toSet() collector method of the static Collectors class of the java.util.stream package;
  • retrieve a List<Double> list from the data stream. In this case, the toList() method of the static Collectors class is used.

 

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

public class StreamAPI {
 
  public static void main(String[] args) {
    // Метод collect() - accumulation of items in a container
    // 1. Create a set of numbers
    ArrayList<Double> AL = new ArrayList<Double>();
    AL.add(1.5);
    AL.add(2.8);
    AL.add(-2.3);
    AL.add(3.4);
    AL.add(1.1);

    // 2. Get a data stream from a list of type ArrayList<Double>
    Stream<Double> stream = AL.stream();

    // 3. Perform the opposite operation - get a set of type Set<Double>
    Set<Double> set;
    set = stream.collect(Collectors.toSet()); // invoke collect()

    // 4. Display set on the screen
    System.out.print("set = { ");
    for (Double t : set)
      System.out.print(t + " ");
    System.out.println("}");

    // 5. Get a new data stream from set
    Stream<Double> stream2 = set.stream();

    // 6. Get a new list of type List<Double> from a new data stream
    List<Double> AL2 = stream2.collect(Collectors.toList());

    // 7. Display new list on screen
    System.out.print("AL2 = [ ");
    for (Double t : AL2)
      System.out.print(t + " ");
    System.out.println("]");
  }
}

Program execution result

set = { 2.8 -2.3 1.5 3.4 1.1 }
AL2 = [ 2.8 -2.3 1.5 3.4 1.1 ]

 

2. Method count(). Get the number of items in a stream. Example

The count() method returns the number of elements in the stream. General form of the method

long count()

The count() method is the final operation.

An example of using the count() method.

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

public class StreamAPI {

  public static void main(String[] args) {
    // The count() method - get the number of elements in a stream
    // 1. Create a set of numbers
    ArrayList<Double> AL = new ArrayList<Double>();
    AL.add(1.5);
    AL.add(2.8);
    AL.add(-2.3);
    AL.add(3.4);
    AL.add(1.1);

    // 2. Get data stream
    Stream<Double> stream = AL.stream();

    // 3. Get the number of elements
    long count = stream.count();
    System.out.println("count = " + count);
  }
}

Program execution result

count = 5

 

3. Method forEach(). Perform an action on each element of the stream. Example

The forEach() method is used when some action (work) needs to be performed on each element of the stream. For example, for convenient display of values of stream elements on the screen.

The general form of the forEach() method is as follows:

void forEach(Consumer<? super T> action)

here

  • Consumer<? super T> – a type that is a standard functional interface. In functional interface, the current element type is limited to some type T (? Super T);
  • action – lambda expression that performs an action on a single element of the stream.

The forEach() method is a terminal operation.

Example. In the example, the following actions are performed on each element of the stream:

  • multiply each element of the stream by 2;
  • display each element of the stream to the screen.

To perform an action forEach() method receives an appropriate lambda expression, realizing functional interface Consumer<Double>.

 

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class StreamAPI {

  public static void main(String[] args) {
    // Method forEach() - perform an action on each element of the stream
    // 1. Create a set of numbers
    ArrayList<Double> AL = new ArrayList<Double>();
    AL.add(1.5);
    AL.add(2.8);
    AL.add(-2.3);
    AL.add(3.4);
    AL.add(1.1);

    // 2. Get a data stream
    Stream<Double> stream = AL.stream();

    // 3. Create a reference to the standard functional interface Consumer<T>
    //    and assign it lambda-expression
    Consumer<Double> action = (value) -> {
      value = value*2; // multiply each element of the stream by 2
      System.out.print(value + " "); // display an element on the screen
    };

    // 4. Use the forEach () method to display stream items on the screen
    stream.forEach(action);
  }
}

Program execution result

3.0 5.6 -4.6 6.8   2.2

 

4. Method max(). Return the maximum element in the data stream. Example

The max() method is designed to get the element with the maximum value in the data stream. The general form of the method is as follows:

Optional<T> max(Comparator<? super T> comparator)

here

  • T – type of data stream elements;
  • Optional<T> – the result containing the largest element value in the data stream. To get an element, you need to use the get() method;
  • comparator – a function for comparing two values of type T as a lambda expression;
  • Comparator<? super T> – a type of the Java standard functional interface used to compare two values of the generic type T.

The max() method is the final operation.

Example. The example declares a Circle class that implements a circle on a coordinate plane. Additionally, a data stream of the Circle type is formed. For the output data stream, a circle with the largest area is determined.

 

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

// A class that implements a circle on a coordinate plane
class Circle {
  // Internal class fields
  private double x, y; // circle center coordinate
  private double radius; // circle radius

  // Constructor
  public Circle(double x, double y, double radius) {
    this.x = x; this.y = y; this.radius = radius;
  }

  // Access methods
  public double getX() { return x; }
  public double getY() { return y; }
  public double getRadius() { return radius; }

  // Method that returns the area of a circle
  public double Area() {
    return Math.PI*radius*radius;
  }
}

public class StreamAPI {

  public static void main(String[] args) {
    // The max() method - determines the largest value in the data stream
    // 1. Create a dataset of type Circle
ArrayList<Circle> AL = new ArrayList<Circle>();
    AL.add(new Circle(2.0, 5.0, 3.3));
    AL.add(new Circle(2.5, 4.2, 3.1));
    AL.add(new Circle(3.1, 4.1, 2.3));
    AL.add(new Circle(4.0, 3.0, 4.3));
    AL.add(new Circle(3.0, 2.0, 1.3));

    // 2. Get a data stream of type Circle from set AL
    Stream<Circle> stream = AL.stream();

    // 3. Declare a comparator - a method for comparing two values of type Circle
    Comparator<Circle> comparator;

    // in a lambda expression, you need to compare two instances of type Circle
    comparator = (circle1, circle2) ->
      (int)(circle1.Area()-circle2.Area());

    // 4. Find the circle with the largest area
    Optional<Circle> maxCircle = stream.max(comparator);

    // 5. Display the result
    System.out.println("maxCircle = (" + maxCircle.get().getX() + "; " +
                       maxCircle.get().getY() + "), radius = " +
                       maxCircle.get().getRadius());
    System.out.println("area = " + maxCircle.get().Area());
  }
}

Program execution result

maxCircle = (4.0; 3.0), radius = 4.3
area = 58.088048164875275

 

5. Method min(). Return the minimum element in the data stream. Example

The min() method allows you to get the element with the minimal value in the data stream. The general form of the method is:

Optional<T> min(Comparator<? super T> comparator)

here

  • T – type of data stream elements;
  • Optional<T> – a result containing the minimum element value in the data stream. To get an element, you need to use the get() method;
  • comparator – a function for comparing two values of type T, which is represented by a lambda expression;
  • Comparator<? super T> – a type of the Java standard functional interface used to compare two values of the generic type T.

The min() method is the final operation.

Example. In the example, based on the stream of segments (lines), the segment with the smallest length is determined. In the data stream, each segment is represented by an instance of the Line class. For a specific segment, the coordinates of the points of its ends are set.

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

// A class that implements the segment specified by the coordinates of points (x1, y1), (x2, y2)
class Line {
  // Internal class fields
  private double x1, y1;
  private double x2, y2;

  // Constructor
  public Line(double _x1, double _y1, double _x2, double _y2) {
    x1 = _x1; y1 = _y1; x2 = _x2; y2 = _y2;
  }

  // Access methods
  public double getX1() { return x1; }
  public double getY1() { return y1; }
  public double getX2() { return x2; }
  public double getY2() { return y2; }

  // Method that returns the length of a segment
  public double length() {
    return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  }
}

public class StreamAPI {

  public static void main(String[] args) {
    // Method min() - get the minimum value of an element in a stream
    // 1. Create a set of lines
    ArrayList<Line> AL = new ArrayList<Line>();
    AL.add(new Line(5.0, 6.0, 8.0, 9.5));
    AL.add(new Line(1.1, 2.3, 8.1, 5.4));
    AL.add(new Line(3.2, 2.8, 1.7, 4.4));
    AL.add(new Line(6.1, 2.5, 3.1, 4.0));
    AL.add(new Line(-1.2, 3.8, -4.3, 2.5));

    // 2. Get data stream of type Line from set AL
    Stream<Line> stream = AL.stream();

    // 3. Declare a comparator - a method for comparing two values of type Line
    Comparator<Line> comparator;
    comparator = (line1, line2) -> {
      // compare the lengths of the segments
      if (line1.length()>line2.length()) return 1;
      if (line1.length()<line2.length()) return -1;
      return 0;
    };

    // 4. Find the line with the minimum length
    Optional<Line> minLine = stream.min(comparator);

    // 5. Display the result
    System.out.println("minLine = ( " + minLine.get().getX1() + "; " +
                       minLine.get().getY1() + "), ( " +
                       minLine.get().getX2() + "; " +
                       minLine.get().getY2() + ")");
    System.out.println("length = " + minLine.get().length());
  }
}

Program execution result:

minLine = ( 3.2; 2.8), ( 1.7; 4.4)
length = 2.1931712199461315

 

6. Method reduce(). Get the specified result from the elements of the stream. Example

The reduce() method refers to reduction operations in the same way as the min(), max(), count() methods. In the reduce() method, you can reduce the stream to a single value according to your own developed criteria.

Examples of such criteria:

  • calculate the sum of the elements of the data stream;
  • calculate the product of the elements of the data stream;
  • other arbitrary criteria.

The reduce() method has several general forms. Below are the two most popular:

Optional<T> reduce(BinaryOperator<T> accumilation_method)
T reduce(T identity_value, BinaryOperator<T> accumilation_method)

here

  • T – the type of elements of the stream;
  • BinaryOperator<T> – the type of the standard functional interface that contains the apply() method. The standard functional interface BinaryOperator<T> is declared in the java.util.function package;
  • accumulation_method – it is a lambda expression that implements the accumulation function. The accumulation function operates on two values and returns some result;
  • identity_value – a value resulting in the same item value being obtained from the data stream. For example, if the element value is x, then for the summation operation identity_value = 0 (0 + x = x). For a multiplication operation identity_value = 1 (1 * x = x).

When writing the code for the accumulation_method operation, you must adhere to the following restrictions:

  • stateless constraint means that each element of the stream is processed separately;
  • constraint without intervention means that the data source does not change in the body of the method (operation);
  • the operation applied to stream elements must be associative (a + b = b + a).

The reduce() method is the terminated operation.

Example. The example defines the sum of the elements of a data stream of type Double.

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class StreamAPI {

  public static void main(String[] args) {
    // The reduce() method - uses a reduce function on stream elements.
    // The example calculates the arithmetic mean of the elements of the data stream
    // 1. Create a dataset of type Double
    ArrayList<Double> AL = new ArrayList<Double>();
    AL.add(25.0);
    AL.add(17.0);
    AL.add(33.0);
    AL.add(18.0);
    AL.add(27.0);
    AL.add(11.0);

    // 2. Get a data stream of type Double from set AL
    Stream<Double> stream = AL.stream();

    // 3. Declare a binary operator that returns type Double
    BinaryOperator<Double> accumulator;

    // 4. For two operands, implement sum calculation
    accumulator = (value1, value2) -> {
      return value1+value2;
    };

    // 5. Call the reduce() function and output the result
    Optional<Double> sum = stream.reduce(accumulator);
    System.out.println("sum = " + sum.get());
  }
}

Program execution result

sum = 131.0

 

7. The toArray() method. Create an array of elements on the calling data stream. Example

The toArray() method is designed to convert the data stream to an array of type Object[]. The method has the following general form:

Object[] toArray()

The method is the final operation.

Example. The example converts a data stream of type Float into an array of type Object[].

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class StreamAPI {

  public static void main(String[] args) {
    // The toArray() method - convert data stream to array of type Object[]
    // 1. Create a set of data of Float type
    ArrayList<Float> AL = new ArrayList<Float>();
    AL.add(25.0f);
    AL.add(11.3f);
    AL.add(3.8f);
    AL.add(7.7f);
    AL.add(2.4f);
    AL.add(5.5f);

    // 2. Get an Integer data stream from the AL set
    Stream<Float> stream = AL.stream();

    // 3. Get the array of type Object[] from the stream
    Object[] AF = stream.toArray();

    // 4. Display the result
    System.out.print("AF = { ");
    for (int i=0; i<AF.length; i++)
      System.out.print(AF[i] + " ");
    System.out.println(" }");
  }
}

Program execution result

AF = { 25.0 11.3 3.8 7.7 2.4 5.5 }

 


Related topics