Stream: Finding Average Length

Stream: Finding Average Length

Stream: Finding Average Length

In this Java code snippet, we’re working with a list of strings: “apple,” “banana,” and “cherry.” Using streams, we transform each string into its corresponding length and convert it to an integer. Then, we calculate the average of these lengths.

If the list is empty, the `orElse` function sets the average to 0.0. This code snippet efficiently computes the average length of the strings, which in this case is approximately 6.33.


List<String> words = Arrays.asList("apple", "banana", "cherry");
double averageLength = words.stream()
.mapToInt(String::length)
.average()
.orElse(0.0);

Java 8 Lambda Expressions Interview Questions with Answers: Mastering the Basics

One thought on “Stream: Finding Average Length

  1. Nice blog here! Also your site loads up fast!
    What host are you using? Can I get your affiliate link
    to your host? I wish my site loaded up as quickly as yours lol

Leave a Reply

Your email address will not be published. Required fields are marked *