Working with Java Streams
A Java stream works like ETL for in-memory data, taking a collection, transforming it step by step, then collecting the result.
Journeyman · Java · Updated
Java Streams are essentially ETL processes for in-memory data sets.
Data Source – E (Extract)
A Java collection, such as an ArrayList, is our data source. The collection must be converted into a stream:
List<String> names = new ArrayList<>();
names.add("Olivia");
names.add("Ethan");
names.add("Sophia");
names.add("Liam");
names.add("Emma");
names.add("Noah");
names.add("Ava");
names.add("Jackson");
names.add("Mia");
names.add("Lucas");
var stream = names.stream();
Transformations – T (Transform)
Many of the Java stream functions perform the transformation tasks.
var stream = names.stream()
.sorted();
Destination – L (Load)
But streams must lead to a final destination, so some of the Java Stream functions allow us to collect the stream of data back into a data at rest state.
var sortedNames = names.stream()
.sorted()
.toList();
Do it: put the class roster in alphabetical order
The coding club keeps its sign-up sheet in the order people signed up. For the roster on the classroom door, the teacher wants the same names in alphabetical order, and the sign-up sheet itself must keep its order: it's how the club knows who signed up first.
The method gets one value:
signUps: the names on the sign-up sheet, aList<String>, in the order people signed up.
For example, with this sign-up sheet:
List<String> signUps = new ArrayList<>(List.of("Olivia", "Ethan", "Sophia", "Liam"));
List<String> roster = rosterFor(signUps);
| Step | ETL | The names |
|---|---|---|
| The sign-up sheet | Extract | Olivia, Ethan, Sophia, Liam |
| Sorted | Transform | Ethan, Liam, Olivia, Sophia |
| The roster | Load | ["Ethan", "Liam", "Olivia", "Sophia"] |
So roster is ["Ethan", "Liam", "Olivia", "Sophia"], and signUps is still ["Olivia", "Ethan", "Sophia", "Liam"].
Your job: write the method rosterFor(List<String> signUps) so it returns a new List<String>: the same names, in alphabetical order.
- Use a stream: from
signUps, sorted, collected into a list. - Don't change
signUps: it keeps the order people signed up in. - When nobody has signed up (an empty list), return an empty list.
Practiced live on the lesson page: write the Java right there and check it.