Write a Java program using Lambda Expression to convert a list of strings to uppercase


The java program that converts a list of strings to uppercase using a lambda expression and a custom functional interface StringConverter. Here's an explanation of the code:

  • The ConvertUppercase class is defined, which contains the main method and another method named convertToUpperCase.
  • Inside the main method:
    • List<String> strings = List.of("Pineapple", "Banana", "Blueberry", "Raspberries", "Grapes");: This line creates an immutable list of strings named strings using the List.of method. It contains a set of strings.
    • System.out.println("Given String : " + strings); : This line prints the original list of strings.
    • List<String> upperstrings = convertToUpperCase(strings, str -> str.toUpperCase());: This line calls the convertToUpperCase method, passing the strings list as well as a lambda expression str -> str.toUpperCase() as the converter. The lambda expression converts each string to uppercase.
    • System.out.println("Convert Uppercase : " + upperstrings);: This line prints the list of strings converted to uppercase.
  • The convertToUpperCase method is defined with the following functionality:
    • List<String> result = new ArrayList<>();: This line creates an ArrayList to store the converted strings.
    • The method iterates through each string in the input list, applies the conversion using the provided converter, and adds the converted string to the result list.
    • Finally, the result list containing the converted strings is returned.
  • The StringConverter functional interface is defined, which declares a single method named convert that takes a string and returns a string. This interface is used to define the lambda expression for converting strings to uppercase.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class ConvertUppercase
{
	public static void main(String[] args)
	{
		List<String> strings = List.of("Pineapple", "Banana", "Blueberry", "Raspberries", "Grapes");
		System.out.println("Givent String : "+strings);
		List<String> upperstrings = convertToUpperCase(strings, str -> str.toUpperCase());
		System.out.println("Convert Uppercase : "+upperstrings);
	}
 
	public static List<String> convertToUpperCase(List<String> list, StringConverter converter)
	{
		List<String> result = new ArrayList<>();
		for (String str : list)
		{
			result.add(converter.convert(str));
		}
		return result;
	}
}
 
interface StringConverter
{
	String convert(String str);
}

Output

Givent String : [Pineapple, Banana, Blueberry, Raspberries, Grapes]
Convert Uppercase : [PINEAPPLE, BANANA, BLUEBERRY, RASPBERRIES, GRAPES]

Example Programs