Hamburger Icon
  • Labs icon Lab
  • Core Tech
Labs

Guided: Java SE 17 Streams Methods

In this hands-on lab, you'll learn how to use Java 17 Streams to provide a concise and expressive way to process data in collections. You'll learn how to use Source, Intermediate operations, and Terminal operations to compose Streams. By the end of the lab, you'll also have explored five common Stream methods: Filtering, Grouping, Finding, Sorting, and Reduction.

Labs

Path Info

Level
Clock icon Intermediate
Duration
Clock icon 40m
Published
Clock icon Jun 21, 2023

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Overview

    Introduction to Java 17 Streams

    Java 17 Streams provide a concise and expressive way to process data in collections. They allow you to perform complex operations on data without having to write a lot of boilerplate code. Streams also support parallel processing, which can improve performance on multi-core systems.

    Streams are composed of three parts:

    • Source: A collection or other data source.
    • Intermediate operations: Operations that transform the data, such as filtering or sorting.
    • Terminal operations: Operations that produce a result or side effect, such as reduction or printing.

    In this lab we will cover 5 common Stream methods:

    1. Filtering
    2. Grouping
    3. Finding
    4. Sorting
    5. Reduction

    Before You Start

    Each section will demonstrate the concept and then you will be given a chance to demonstrate your learning through a task.

    All of your code will be written in Unsolved.java.

    You are encouraged to complete the tasks on your own but if you need help, feel free to peek at the Solved.java file.

    If you are ready to get started, click the arrow below to begin.

  2. Challenge

    Filtering

    Filtering

    Filtering is the process of selecting elements from a collection based on a condition. Streams provide the filter() method to perform this operation. The filter() method takes a Predicate object that defines the condition for filtering.

    This Java code creates a list of numbers, filters out the ones that are greater than 10 using a stream, and then prints the resulting filtered list.

    public class NumberStreamExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 30, 25);
    
            // Filter numbers that are greater than 10
            List<Integer> filteredNumbers = numbers.stream()
                    .filter(number -> number > 10)
                    .collect(Collectors.toList());
            System.out.println("Filtered numbers: " + filteredNumbers);
        }
    }
    
    

    Your Task

    • Inside Unsolved.java complete filteredWords so that it filters all the words that start with "a" and prints them to the screen.
    • Use the example above as a guide.
    • Execute the test command in the terminal to run the test suite.

    Successful Output

    Filtered words: [apple, avacado, almonds]

  3. Challenge

    Grouping

    Grouping

    Grouping is the process of dividing elements of a collection into groups based on a criteria. Streams provide the groupingBy() method to perform this operation. The groupingBy() method takes a Function object that defines the criteria for grouping.

    This Java code uses a stream to group a list of numbers by their parity (even or odd) and outputs the result.

    public class NumberStreamExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 30, 25);
          
    			// Group numbers by their parity (even or odd)
            Map<Boolean, List<Integer>> numbersByParity = numbers.stream()
                    .collect(Collectors.partitioningBy(number -> number % 2 == 0));
            System.out.println("Numbers grouped by parity: " + numbersByParity);
        }
    }
    

    Your Task

    • Inside Unsolved.java complete wordsByLength so that it groups the words by their length and prints it to the screen.
    • Use the example above as a guide.
    • Execute the test command in the terminal to run the test suite.

    Successful Output

    Words grouped by length: {3=[cat, dog], 4=[fish], 5=[apple], 6=[banana], 7=[avacado, almonds], 8=[elephant]}

  4. Challenge

    Finding

    Finding

    Finding is the process of searching for an element in a collection based on a condition. Streams provide several methods for performing finding, such as findAny() and findFirst().

    This Java code creates a list of numbers, uses a stream to find the maximum number in the list, and prints it to the console.

    public class NumberStreamExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 30, 25);
    
            // Find the maximum number
            Optional<Integer> maxNumber = numbers.stream()
                    .max(Integer::compareTo);
            System.out.println("Maximum number: " + maxNumber.orElse(0));
        }
    }
    
    

    Your Task

    • Inside Unsolved.java complete anyWordWithT so that it finds any word that ends in "t" and prints it to the screen.
    • Use the example above as a guide.
    • Execute the test command in the terminal to run the test suite.

    Successful Output

    Any word with 't': cat

  5. Challenge

    Sorting

    Sorting

    Sorting is the process of arranging elements of a collection in a specific order. Streams provide the sorted() method to perform this operation. The sorted() method takes a Comparator object that defines the order in which elements should be sorted.

    This Java code takes a list of integers, sorts them in descending order using a stream and comparator, and then prints out the sorted list.

    public class NumberStreamExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 30, 25);
    				
            // Sort numbers in descending order
            List<Integer> sortedNumbers = numbers.stream()
                    .sorted(Comparator.reverseOrder())
                    .collect(Collectors.toList());
            System.out.println("Sorted numbers: " + sortedNumbers);
        }
    }
    

    Your Task

    • Inside Unsolved.java complete sortedWords so that it sorts the words in reverse order and prints them to the screen.
    • Use the example above as a guide.
    • Execute the test command to run the tests.

    Output:

    Sorted words: [fish, elephant, dog, cat, banana, avacado, apple, almonds]

  6. Challenge

    Reduction

    Reduction

    Reduction is the process of combining elements of a collection into a single value. Streams provide several methods for performing reduction, such as reduce() and collect().

    This code uses a number stream to reduce a list of integers to their sum and print the result.

    public class NumberStreamExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 30, 25);
    
            // Reduce numbers to their sum
            int reducedNumbers = numbers.stream()
                    .reduce(0, Integer::sum);
            System.out.println("Reduced numbers: " + reducedNumbers);
        }
    }
    

    Your Task

    • Inside Unsolved.java complete educedWords so that it reduces words to a comma-separated string and prints them to the screen.
    • Use the example above as a guide.
    • Execute the test command in the terminal to run the test suite.

    Successful Output

    Reduced words: apple, banana, cat, avacado, almonds, dog, elephant, fish

Danny Sullivan is a former special education teacher and professional baseball player that moved into software development in 2014. He’s experienced with Ruby, Python and JavaScript ecosystems, but enjoys Ruby most for its user friendliness and rapid prototyping capabilities.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.