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


The java program that uses Java Streams to convert a list of strings to uppercase and lowercase. Here's an explanation of the code:

  • import java.util.Arrays;: This line imports the Arrays class from the java.util package. It's used to create a list of strings from an array.
  • import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
  • import java.util.stream.Collectors;: This line imports the Collectors class from the java.util.stream package, which is used to collect elements from a Stream into a collection.
  • The StringConverter class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<String> strings = Arrays.asList("Tutor", "Joes", "Computer", "Education");: This line creates a list of strings named strings containing the elements "Tutor," "Joes," "Computer," and "Education."
    • List<String> upr_str = strings.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());: This line converts the strings in the strings list to uppercase using a stream. The map operation applies the toUpperCase method to each string, and the collect operation collects the results into a new list named upr_str.
    • List lwr_str = strings.stream().map(str -> str.toLowerCase()).collect(Collectors.toList());: This line similarly converts the strings to lowercase and collects the results into a new list named lwr_str.
    • System.out.println("Uppercase Strings : " + upr_str);: This line prints the list of uppercase strings.
    • System.out.println("Lowercase Strings : " + lwr_str);: This line prints the list of lowercase strings.

The code uses Java Streams to efficiently and concisely convert the strings to uppercase and lowercase. When you run the program, it will display the original list of strings, the list of strings converted to uppercase, and the list of strings converted to lowercase.

Source Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class StringConverter
{
	public static void main(String[] args)
	{
		List<String> strings = Arrays.asList("Tutor", "Joes", "Computer", "Education");
 
		List<String> upr_str = strings.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());
 
		List<String> lwr_str = strings.stream().map(str -> str.toLowerCase()).collect(Collectors.toList());
 
		System.out.println("Uppercase Strings : " + upr_str);
		System.out.println("Lowercase Strings : " + lwr_str);
	}
}

Output

Uppercase Strings : [TUTOR, JOES, COMPUTER, EDUCATION]
Lowercase Strings : [tutor, joes, computer, education]

Example Programs