image

Acesse bootcamps ilimitados e +650 cursos pra sempre

70
%OFF
Article image
Roberto Nascimento
Roberto Nascimento20/03/2026 19:55
Compartilhe
Luizalabs - Back-end com Python - 2º EdiçãoRecomendados para vocêLuizalabs - Back-end com Python - 2º Edição

Breve Intro. às Streams and Lambda Expressions

    Streams, in conjuction with lambdas, allow developers to process data from Collections in a powerful way. They can be used to simplify the code and make it more efficient.

    Using Aggregate Operations

    - When we work with Collections, we generally do more than put the objects into it; we also need store, retrieve, update and delete them.

    - These operations use lambda to perform actions on the objects in a Collection:

    a. Print names of people from a Collection of Address objects.

    b. Return all of the Address objects for people from Akron, Ohio.

    c. Calculate and return the average age of servers in your inventory (provided the Server object has a purchase date field).

    Conceptual Workflow

    - As an assembly line, the Streams starts with a box of Server objects and ends with a single number.

    1. Stream: Take the list of Servers.
    2. Map: For each server, subtract the purchaseDate from Today's Date. This gives you the age in years.
    3. Average: Sum those ages up and divide by the count.

    Code Implementation

    - To translate the previous logic to a Stream, we typically use the java.time (JSR-310) library.

    import java.time.LocalDate;
    import java.time.Period;
    
    public double getAverageServerAge(List<Server> inventory) {
    
    return inventory.stream()
    
    // Step 1: Convert Server object to an Integer (Age)
    .mapToInt(server -> {
    LocalDate today = LocalDate.now();
    return Period.between(server.getPurchaseDate(), today).getYears();
    })
    
    // Step 2: Use the specialized average() terminal operation
    .average()
    
    // Step 3: Handle the case where the list might be empty
    .orElse(0.0);
    
    }
    

    - These tasks can be accomplished by using aggregate operations along with pipelines and streams.

    Understanding Pipelines and Streams

    - Pipeline: sequence of aggregate operations.

    - Stream: sequence of items (not a data structure) that carries items from the source through the pipeline.

    - Pipelines include: data source (commonly a Collection, but can be an array, the return from a method call, or some sort of I/O channel), zero or more intermediate operations, and a terminal operation.

    - Intermediate operations: such as a filter operation (returns items based on a criteria), accept a stream and produce a new stream.

    - Terminal operation: returns a nonstream result (a primitive type, a Collection, or not result at all, for example, printing the name of each item in the stream).

    Streams vs. Iteration

    - Aggregate operations process items from a stream, not directly from a Collection.

    - Aggregate operations support lambda expressions as parameters.

    - We also have a aggregate operation named forEach, that looks like a iterator.

    Exploring Lambdas

    - In programming, we have functions called anonymous functions (functions without specific name) that can take parameters, have a body, and return data.

    - As far as Java is concerned, such anonymous functions are named Lambda expressions, and they are implementations of funcional interfaces.

    - Funcional Interface: an interface with a single abstract method (e.g., Runnable and Comparable interfaces).

    - Lambda expressions can be passed into methods as parameters (now we can pass methods into methods; not only data into methods; we have now code been treated as data).

    - They are particularly useful with stream and aggregate operation features of Java;

    - In Aggregate operations as filter and forEach, the lambda expression defines how the objects in the stream should be filtered or processed.

    The forEach() Stream Method

    • It doesn't return anything; it allows to run code on each object in the stream; in the example below, each person's data is being printed out.
    people.stream()
      .forEach((p) -> System.out.printf("%s : %d", p.getName(), p.getAge()));
    people.stream()
      .forEach((p) -> System.out.printf("%s : %d", p.getName(), p.getAge()));
    

    - The lambda passed in this example implements the functional interface Consumer; that interface includes the abstract method accept.

    Compartilhe
    Recomendados para você
    Lupo - Primeiros Passos com Inteligência Artificial
    Almaviva - Back-end com Java & QA
    Luizalabs - Back-end com Python - 2º Edição
    Comentários (0)
    Recomendados para vocêLuizalabs - Back-end com Python - 2º Edição