Class StreamExamples

java.lang.Object
net.jrodolfo.java_evolution.java08.StreamExamples

public class StreamExamples extends Object
Demonstrates the Stream API introduced in Java 8.

Before Java 8, collection processing usually meant writing loops, temporary collections, counters, and mutable variables. That style works, but the intent can be hidden behind the mechanics of iteration.

Streams solve this by representing data processing as a pipeline of operations such as filter, map, sorted, and collect. The code can describe what result is wanted instead of spelling out every loop step. The examples here return values instead of printing output so tests can document the expected behavior.

  • Constructor Details

    • StreamExamples

      public StreamExamples()
  • Method Details

    • activeUserNames

      public List<String> activeUserNames(List<StreamExamples.User> users)
      Finds active users, extracts their names, and sorts the result.
      Parameters:
      users - the users to process
      Returns:
      active user names in alphabetical order
    • namesByDepartment

      public Map<String, List<String>> namesByDepartment(List<StreamExamples.User> users)
      Groups user names by department with Collectors.groupingBy(Function).
      Parameters:
      users - the users to group
      Returns:
      a map where each department points to the names in that department
    • totalAgeOfActiveUsers

      public int totalAgeOfActiveUsers(List<StreamExamples.User> users)
      Uses a primitive IntStream to sum ages without boxing every value as an Integer.
      Parameters:
      users - the users to inspect
      Returns:
      the sum of ages for active users
    • longestName

      public String longestName(List<StreamExamples.User> users)
      Uses max with a comparator to find the longest user name.
      Parameters:
      users - the users to inspect
      Returns:
      the longest name, or an empty string when the list has no users