View Javadoc
1   package fr.univtln.bruno.samples.java101.tp3.functional;
2   
3   import fr.univtln.bruno.samples.java101.tp3.Person;
4   import lombok.extern.slf4j.Slf4j;
5   
6   import java.util.List;
7   import java.util.Map;
8   import java.util.stream.Collectors;
9   
10  /**
11   * Applied functional examples that operate on collections using the Stream API.
12   *
13   * <p>These examples were moved from other TP3 subpackages to centralize all
14   * functional idioms in the `functional` package.</p>
15   */
16  @Slf4j
17  public class AppliedFunctionnalExamples {
18  
19    /**
20     * Private constructor to prevent instantiation.
21     */
22    private AppliedFunctionnalExamples() {
23      // utility class
24    }
25  
26    /**
27     * Demonstrate mapping and collecting on a list of Person instances.
28     */
29    public static void listStreamsExample() {
30      log.info("=== List stream mapping example ===");
31      List<Person> people = List.of(
32        Person.of("Charlie", "Brown", 35),
33        Person.of("Alice", "Smith", 30),
34        Person.of("Bob", "Jones", 25)
35      );
36      log.info("Original names: {}", people.stream().map(Person::getFullName).toList());
37      log.info("Names with ages: {}", people.stream().map(p -> p.getFullName() + "(" + p.age() + ")").toList());
38    }
39  
40    /**
41     * Demonstrate streaming over grouped values (e.g. after a grouping operation) to extract names.
42     */
43    public static void mapStreamGroupingExample() {
44      log.info("=== Map grouping stream example ===");
45      List<Person> people = List.of(
46        Person.of("Alice", "Smith", 30),
47        Person.of("Bob", "Jones", 25),
48        Person.of("Charlie", "Brown", 35),
49        Person.of("David", "Smith", 40)
50      );
51      Map<String, List<Person>> byLast = people.stream().collect(Collectors.groupingBy(Person::lastName));
52      byLast.forEach((ln, ps) -> log.info("{} -> {}", ln, ps.stream().map(Person::getFullName).toList()));
53    }
54  
55    /**
56     * Runner for applied functional examples.
57     *
58     * @param args ignored
59     */
60    public static void main(String[] args) {
61      listStreamsExample();
62      mapStreamGroupingExample();
63    }
64  }