Class StreamExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.StreamExamples
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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSmall Java 8-style data class used by the stream examples. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionactiveUserNames(List<StreamExamples.User> users) Finds active users, extracts their names, and sorts the result.longestName(List<StreamExamples.User> users) Usesmaxwith a comparator to find the longest user name.namesByDepartment(List<StreamExamples.User> users) Groups user names by department withCollectors.groupingBy(Function).intUses a primitiveIntStreamto sum ages without boxing every value as anInteger.
-
Constructor Details
-
StreamExamples
public StreamExamples()
-
-
Method Details
-
activeUserNames
Finds active users, extracts their names, and sorts the result.- Parameters:
users- the users to process- Returns:
- active user names in alphabetical order
-
namesByDepartment
Groups user names by department withCollectors.groupingBy(Function).- Parameters:
users- the users to group- Returns:
- a map where each department points to the names in that department
-
totalAgeOfActiveUsers
Uses a primitiveIntStreamto sum ages without boxing every value as anInteger.- Parameters:
users- the users to inspect- Returns:
- the sum of ages for active users
-
longestName
Usesmaxwith 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
-