w3resource

Java Program: Lambda expression to find average string length


23. Find average string length using lambda

Write a Java program to implement a lambda expression to find the average length of strings in a list.

Sample Solution:

Java Code:

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List <String> colors = Arrays.asList("Red", "Black", "White", "Orange", "Blue");
    System.out.println("List of colors: " + colors);

    double averageLength = calculateAverageLength(colors);
    System.out.println("Average length of colors(strings): " + averageLength);
  }

  public static double calculateAverageLength(List < String > strings) {
    return strings.stream()
      .mapToInt(String::length) // Convert each string to its length
      .average() // Calculate the average
      .orElse(0); // If the list is empty, return 0 as the default value
  }
}

Sample Output:

List of colors: [Red, Black, White, Orange, Blue]
Average length of colors(strings): 4.6

Explanation:

In the above exercise,

The main() method creates a list of strings (strings) containing four elements.

Following are the steps taken by the calculateAverageLength method when given a list of strings:

  • The stream() method is used on the strings list to create a stream of strings.
  • The mapToInt method converts each string to its length by using a method reference String::length.
  • The average method calculates the average length of the strings in the stream.
  • The orElse method is used to provide a default value of 0 if the list is empty.

The calculated average length is returned by the calculateAverageLength method and stored in the averageLength variable.

Flowchart:

Flowchart: Java  Exercises: Sort list of objects with lambda expression.


For more Practice: Solve these Related Problems:

  • Write a Java program to implement a lambda expression that maps each string in a list to its length and then calculates the average.
  • Write a Java program to create a lambda that computes the average length of strings after filtering out empty entries.
  • Write a Java program to implement a lambda expression that calculates the total character count and divides it by the number of strings using reduce().
  • Write a Java program to chain lambda expressions to convert a list of strings to lengths and then compute their average using summary statistics.

Go to:


Improve this sample solution and post your code through Disqus

PREV : Check case of strings in list using lambda.
NEXT : Find largest prime factor using lambda.

Live Demo:

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.