Java. Examples of solving problems on data streams




Examples of solving tasks on data streams, which are objects of the developed classes


Contents


Search other websites:

1. Class Car. Example
1.1. Task

Create a class Car. The following information should be stored in the class:

  • the name of the car;
  • year of issue;
  • cost;
  • colour;
  • engine volume.

You need to create a set of cars and complete the following tasks:

  • display all cars;
  • display cars of the specified color
  • display cars more expensive than the specified price;
  • display cars whose year of manufacture is in the specified range;
  • sort cars in descending order of value.

Solve the tasks using the Stream API.

 

1.2. Solution

The text of the program that solves this task is as follows.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;

class Car {
  private String name;
  private int year;
  private String color;
  private double volume;
  private double price;

  // Constructor
  public Car(String _name, String _color, int _year, double _volume, double _price) {
    name = _name; year = _year; color = _color;
    volume = _volume; price = _price;
  }

  // Methods of type get()
  String getName() { return name; }
  int getYear() { return year; }
  String getColor() { return color; }
  double getVolume() { return volume; }
  double getPrice() { return price; }
}

public class StreamAPI {

  // 1. Display all cars
  public static void PrintAllCars(ArrayList<Car> AL) {
    // 1. Get the Stream<Car> stream
    Stream<Car> stream = AL.stream();

    // 2. Implement the standard functional interface Consumer<T>
    Consumer<Car> action = (n) -> {
      System.out.println(n.getName() + ", " + n.getColor() +
                         ", " + n.getPrice() + ", " + n.getYear() +
                         ", " + n.getVolume());
    };

    // 3. Display all cars
    stream.forEach(action);

    // 4. Same
    /*
      AL.stream().forEach((n) -> System.out.println(n.getName() + ", " +
      n.getColor() +    ", " +
      n.getPrice() + ", " +
      n.getYear() + ", " +
      n.getVolume())); 
    */
  }

  // 2. Display all cars of the specified color
  public static void PrintAllCarsColor(ArrayList<Car> AL, String color) {
    // 1. Get the stream
    Stream<Car> stream = AL.stream();

    // 2. Reference to Predicate<T>
    Predicate<Car> predicate = (car) -> {
      if (car.getColor()==color)
        return true;
      return false;
    };

    // 3. Get a new stream according to the predicate
    Stream<Car> filterStream = stream.filter(predicate);

    // 4. Display a new filtered stream
    // 4.1. Reference to the standard interface Consumer<T>
    Consumer<Car> action = (n) -> {
      System.out.println(n.getName() + ", " + n.getColor() +
                         ", " + n.getPrice() + ", " + n.getYear() +
                         ", " + n.getVolume());
    };

    // 4.2. Output of each element with the forEach() method
    filterStream.forEach(action);
  }

  // 3. Display all cars above the specified price
  public static void PrintAllCarsPrice(ArrayList<Car> AL, double price) {
    // 1. Get the stream
    Stream<Car> stream = AL.stream();

    // 2. A reference to Predicate<T>
    Predicate<Car> predicate = (car) -> {
      if (car.getPrice()>price)
        return true;
      return false;
    };

    // 3. Get a new stream according to a predicate
    Stream<Car> filterStream = stream.filter(predicate);

    // 4. Output a new filtered stream
    // 4.1. Reference to the standard functional interface Consumer<T>
    Consumer<Car> action = (n) -> {
      System.out.println(n.getName() + ", " + n.getColor() +
                         ", " + n.getPrice() + ", " + n.getYear() +
                         ", " + n.getVolume());
    };

    // 4.2. Output of each element with the forEach() method
    filterStream.forEach(action);
  }

  // 4. Display vehicles whose year of manufacture is within the specified range
  public static void PrintAllCarsYear(ArrayList<Car> AL, int year1, int year2) {
    // 1. Declare a reference to Predicate<T> and assign a lambda expression to this reference
    Predicate<Car> predicate = (car) ->
      (car.getYear()>=year1)&&(car.getYear()<=year2);

    // 2. Get the resulting stream according to the predicate
    Stream<Car> stream = AL.stream().filter(predicate);

    // 3. Output the resulting stream
    // 3.1. Declare a reference to the standard functional interface Consumer<T>
    Consumer<Car> action;

    // 3.2. Assign a lambda expression to the action reference that displays information about the car
    action = (car) -> {
      System.out.println(car.getName() + ", " + car.getColor() +
                         ", " + car.getYear() + ", " + car.getPrice() + ", " + car.getVolume());
    };

    // 3.3. Display the stream
    stream.forEach(action);
  }

  // 5. Display cars sorted by price
  public static void PrintCarsSortedByPrice(ArrayList<Car> AL) {
    // 1. Declare a reference to the Comparator<T> functional interface
    Comparator<Car> comparator;

    // 2. Assign a lambda expression to the reference that compares two values
    comparator = (car1, car2) -> {
      // The lambda expression must return an int result:   <0, ==0, >0
      // Sort descending: car2 - car1.
      return (int)(car2.getPrice()-car1.getPrice()); // Compare costs
    };

    // 4. Get a sorted stream. To sort, use the sorted() method.
    Stream<Car> sortedStream = AL.stream().sorted(comparator);

    // 5. Display the stream
    // 5.1. Declare a reference to the Consumer<T> interface
    //     and assign it a lambda expression that outputs vehicle data
    Consumer<Car> action = (car) -> {
      System.out.println(
                         car.getName() + ", " +
                         car.getColor() + ", " +
                         car.getYear() + ", " +
                         car.getPrice() + ", " +
                         car.getVolume()
                        );
    };

    // 5.2. Display the sortedStream stream
    sortedStream.forEach(action);
  }

  public static void main(String[] args) {
    // 1. Form the array under test
    ArrayList<Car> AL = new ArrayList<Car>();
    AL.add(new Car("BMW", "Black", 2018, 2.2, 18800.0));
    AL.add(new Car("Audi", "Silver", 2017, 2.3, 20500.0));
    AL.add(new Car("Renault", "Red", 2018, 1.5, 11800.0));
    AL.add(new Car("Audi", "Silver", 2016, 2.5, 22800.0));
    AL.add(new Car("Renault", "Silver", 2017, 1.3, 10250.0));
    AL.add(new Car("VW", "Red", 2017, 2.3, 15800.0));
    AL.add(new Car("Mercedes", "White", 2018, 2.5, 25800.0));

    // 2. Display all cars
    StreamAPI.PrintAllCars(AL);

    // 3. Display cars of the specified color
    System.out.println("---------------------------------");
    StreamAPI.PrintAllCarsColor(AL, "Silver");

    // 4. Display cars more expensive than the specified price
    System.out.println("---------------------------------");
    StreamAPI.PrintAllCarsPrice(AL, 20000.0);

    // 5. Display vehicles whose year of manufacture is within the specified range
    System.out.println("---------------------------------");
    StreamAPI.PrintAllCarsYear(AL, 2018, 2018);

    // 6. Sort cars in descending order of value
    System.out.println("---------------------------------");
    System.out.println("Sorting by descending sort");
    StreamAPI.PrintCarsSortedByPrice(AL);
  }
}

The result of the program execution:

BMW, Black, 18800.0, 2018, 2.2
Audi, Silver, 20500.0, 2017, 2.3
Renault, Red, 11800.0, 2018, 1.5
Audi, Silver, 22800.0, 2016, 2.5
Renault, Silver, 10250.0, 2017, 1.3
VW, Red, 15800.0, 2017, 2.3
Mercedes, White, 25800.0, 2018, 2.5
---------------------------------
Audi, Silver, 20500.0, 2017, 2.3
Audi, Silver, 22800.0, 2016, 2.5
Renault, Silver, 10250.0, 2017, 1.3
---------------------------------
Audi, Silver, 20500.0, 2017, 2.3
Audi, Silver, 22800.0, 2016, 2.5
Mercedes, White, 25800.0, 2018, 2.5
---------------------------------
BMW, Black, 2018, 18800.0, 2.2
Renault, Red, 2018, 11800.0, 1.5
Mercedes, White, 2018, 25800.0, 2.5
---------------------------------
Sorting by descending sort
Mercedes, White, 2018, 25800.0, 2.5
Audi, Silver, 2016, 22800.0, 2.5
Audi, Silver, 2017, 20500.0, 2.3
BMW, Black, 2018, 18800.0, 2.2
VW, Red, 2017, 15800.0, 2.3
Renault, Red, 2018, 11800.0, 1.5
Renault, Silver, 2017, 10250.0, 1.3

 

2. Working with streams of objects of generalized (template) classes. The Point<T> class. Example
2.1. Task

Develop a generic (template) Point class that implements a point on the coordinate plane (x; y).

Based on the developed class Point, create a set of objects. Implement the following tasks for the created set of objects:

  • get the point (object) with the largest x-coordinate value;
  • create a new stream of numbers double. Each number is the distance from a point to the origin. Display the resulting stream;
  • create a new stream of objects. There must be points (objects) in the stream, the distance from which to the origin is more than 5;
  • sort objects in descending order by distance from point to origin.

Place the solution of tasks in the Solution class, which will contain 4 generalized methods that will solve the tasks according to the condition.

When solving the problem, use the Stream API tools.

 

2.2. Solution

The text of the program that solves this problem is as follows.

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

// Templated class that implements a point on a coordinate plane
class Point<T extends Number> {
  // Internal class fields
  private T x;
  private T y;

  // Constructor
  public Point(T x, T y) {
    this.x = x; this.y = y;
  }

  // Access methods for class fields
  public T getX() { return x; }
  public T getY() { return y; }
}

// Class - problem solution
class Solution {
  // 1. Get the point (object) with the largest x coordinate value
  public <T extends Number> Point<T> getMaxCoordX(ArrayList<Point<T>> AL) {
    // 1. Get data stream from the array
    Stream<Point<T>> stream = AL.stream();

    // Implement comparator - comparison method returning <0, ==0, >0
    // depending on whether the x coordinate of point 2 is greater than the x coordinate of point 1
    Comparator<Point<T>> comparator;

    comparator = (point1, point2) -> {
      // get x coordinates of points point1, point2
      T x2 = point2.getX();
      T x1 = point1.getX();

      if (x2.doubleValue()>x1.doubleValue())
        return -1;
      if (x2.doubleValue()<x1.doubleValue())
        return 1;
      return 0;
    };

    // 3. Calculate Point<T> with maximum x value
    Optional<Point<T>> maxPt = stream.max(comparator);

    // 4. Return found point
    return maxPt.get();
  }

  // A method that forms a new stream of type double.
  // Elements of the stream are distances from a point to the origin.
  public <T extends Number> Stream<Double> getStreamLengthOrigin(ArrayList<Point<T>> AL) {
    // 1. Get stream of points from array AL
    Stream<Point<T>> stream = AL.stream();

    // 2. Generate a function for obtaining a double value from a Point<T> type
    // 2.1. Declare a reference to the standard functional interface Function<T, R>
    Function<Point<T>, Double> function;

    // 2.2. Generate a lambda expression
    //      that returns the distance from point to the origin
    function = (point) -> {
      double x = point.getX().doubleValue();
      double y = point.getY().doubleValue();
      return (double)(Math.sqrt(x*x+y*y));
    };

    // 3. Use function with map() method
    Stream<Double> streamOrigin = stream.map(function);

    // 4. Return the result
    return streamOrigin;
  }

  // Create a new stream of objects. The stream must contain points (objects),
  // the distance from which to the origin is greater than 5.
  public <T extends Number> Stream<Point<T>> getPointsLength5(ArrayList<Point<T>> AL) {
    // 1. Get stream of points from array AL
    Stream<Point<T>> stream = AL.stream();

    // 2. Generate a predicate (condition) that will be used when forming a new stream
    // 2.1. Declare a reference to the Predicate<T> standard functional interface
    Predicate<Point<T>> predicate;

    // 2.2. Assign lambda expression to the reference
    predicate = (point) -> {
      // calculate distance length from point to origin
      double x = point.getX().doubleValue();
      double y = point.getY().doubleValue();
      double length = Math.sqrt(x*x+y*y);

      // check the value of length
      if (length>5.0)
        return true;
      return false;
    };

    // 3. Form a new stream
    Stream<Point<T>> streamLength5 = stream.filter(predicate);

    // 4. Return the result
    return streamLength5;
  };

  // Sort objects in descending order by distance from point to origin.
  public <T extends Number> Stream<Point<T>> getSortedPoints(ArrayList<Point<T>> AL) {
    // 1. Get stream of points from array AL
    Stream<Point<T>> stream = AL.stream();

    // 2. Generate Comparator - A method that compares the distances from two points to the origin.
    //   The method returns a value of type int, respectively <0, ==0, >0.
    Comparator<Point<T>> comparator = (point1, point2) -> {
      // 2.1. Determine distances from points point1, point2 to the origin
      double x1 = point1.getX().doubleValue();
      double y1 = point1.getY().doubleValue();
      double x2 = point2.getX().doubleValue();
      double y2 = point2.getY().doubleValue();
      double length1 = Math.sqrt(x1*x1+y1*y1);
      double length2 = Math.sqrt(x2*x2+y2*y2);

      // 2.2. Return the result
      return (int)(length2-length1);
    };

    // 3. Call the sort method
    Stream<Point<T>> sortedStream = stream.sorted(comparator);

    // 4. Return a sorted stream
    return sortedStream;
  }
}

public class StreamAPI {

  public static void main(String[] args) {
    // Stages of solving the problem
    // 1. Create a set of objects of type Point ().
    //   Generate coordinates value randomly.
    ArrayList<Point<Integer>> AL = new ArrayList<Point<Integer>>();
    Point<Integer> pt;
    int x, y;

    // 10 points are created
    for (int i=0; i<10; i++) {
      x = (int)(Math.random()*10);
      y = (int)(Math.random()*10);
      pt = new Point<Integer>(x, y);
      AL.add(pt);
    }

    // Display an array of points on the screen
    System.out.print("AL = [");
    for (Point<Integer> t : AL) {
      System.out.print("(" + t.getX() + "," + t.getY() + ") ");
    }
    System.out.println("]");

    // 2. Implement the solution. To do this, you need to create an instance
    //   of the Solution class and call the methods of this instance in turn.
    Solution solution = new Solution();

    // 2.1. Task 1. Solution
    Point<Integer> maxPt = solution.getMaxCoordX(AL);

    System.out.println("Solution 1. Max Point.");
    System.out.println("maxPt = (" + maxPt.getX().intValue() +
                                 ", " + maxPt.getY().intValue() + ")");

    // 2.2. Task 2. Solution
    Stream<Double> streamOrigin = solution.getStreamLengthOrigin(AL);

    // Display the streamOrigin to the screen
    System.out.println("Solution 2. Array of lengths.");

    Consumer<Double> action = (n) -> {
      System.out.println(n + " ");
    };
    streamOrigin.forEach(action);

    // 2.3. Task 3. Solution
    Stream<Point<Integer>> streamPoints = solution.getPointsLength5(AL);

    // Display the result of task 3
    System.out.println("Solution 3. Points with length>5.0");
    Consumer<Point<Integer>> action2 = (point) -> {
      System.out.println("("+point.getX()+"; " + point.getY() + ")");
    };
    streamPoints.forEach(action2);

    // 2.4. Task 4. Solution
    Stream<Point<Integer>> streamSorted = solution.getSortedPoints(AL);
    System.out.println("Solution 4. Sorting points.");

    // Display the result of task 4
    streamSorted.forEach(action2);
  }
}

Program execution result:

AL = [(9,2) (7,4) (3,3) (8,2) (4,7) (8,6) (0,1) (0,2) (4,6) (4,6) ]
Solution 1. Max Point.
maxPt = (9, 2)
Solution 2. Array of lengths.
9.219544457292887
8.06225774829855
4.242640687119285
8.246211251235321
8.06225774829855
10.0
1.0
2.0
7.211102550927978
7.211102550927978
Solution 3. Points with length>5.0
(9; 2)
(7; 4)
(8; 2)
(4; 7)
(8; 6)
(4; 6)
(4; 6)
Solution 4. Sorting points.
(9; 2)
(8; 6)
(7; 4)
(8; 2)
(4; 7)
(4; 6)
(4; 6)
(3; 3)
(0; 2)
(0; 1)

 


Related topics