Site icon Java Guidance

Stream: Finding Average Length

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

Exit mobile version