Write a Java program using Lambda Expression to convert a list of strings to uppercase if the string length is even and to lowercase if the string length is odd


The java program that transforms a list of strings based on the length of each string. If a string's length is even, it converts the string to uppercase; otherwise, it converts the string to lowercase. The program uses Java Streams and the map operation to perform this transformation. Here's an explanation of the code:

  • An ArrayList named fruits is created to store a list of strings.
  • The original list of strings, named fruits, is populated with various fruit names.
  • System.out.println("Original Strings : " + fruits); prints the original list of strings.
  • The program uses a Java Stream to transform the strings based on their length:
    • fruits.stream(): This converts the fruits list into a stream of strings.
    • .map(s -> (s.length() % 2 == 0) ? s.toUpperCase() : s.toLowerCase()): This is a map operation that applies a lambda expression to each string in the stream. If a string's length is even (i.e., the result of s.length() % 2 is 0), it converts the string to uppercase using s.toUpperCase(). Otherwise, it converts the string to lowercase using s.toLowerCase().
    • .collect(Collectors.toList()): This collects the transformed strings into a new list named modifiedstrings.
  • System.out.println("Modified Strings : " + modifiedstrings); prints the list of strings after the transformation.

Source Code

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
public class ConvertCaseBasedOnLength
{
	public static void main(String[] args)
	{
		List<String> fruits = new ArrayList<>();
		fruits.add("Apple");
		fruits.add("Banana");
		fruits.add("Raspberries");
		fruits.add("Cherry");
		fruits.add("Mango");
		fruits.add("Date");
		fruits.add("Watermelon");
 
		System.out.println("Original Strings : " + fruits);
 
		List<String> modifiedstrings = fruits.stream().map(s -> (s.length() % 2 == 0) ? s.toUpperCase() : s.toLowerCase()).collect(Collectors.toList());
 
		System.out.println("Modified Strings : " + modifiedstrings);
	}
}

Output

Original Strings : [Apple, Banana, Raspberries, Cherry, Mango, Date, Watermelon]
Modified Strings : [apple, BANANA, raspberries, CHERRY, mango, DATE, WATERMELON]

Example Programs