w3resource

Java Program: Convert List of Strings to Uppercase or Lowercase using Streams

Java Stream: Exercise-2 with Solution

Write a Java program to convert a list of strings to uppercase or lowercase using streams.

Sample Solution:

Java Code:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    List < String > colors = Arrays.asList("RED", "grEEn", "white", "Orange", "pink");
    System.out.println("List of strings: " + colors);
    // Convert strings to uppercase using streams
    List < String > uppercaseStrings = colors.stream()
      .map(String::toUpperCase)
      .collect(Collectors.toList());

    System.out.println("\nUppercase Strings: " + uppercaseStrings);

    // Convert strings to lowercase using streams
    List < String > lowercaseStrings = colors.stream()
      .map(String::toLowerCase)
      .collect(Collectors.toList());

    System.out.println("Lowercase Strings: " + lowercaseStrings);
  }
}

Sample Output:

List of strings: [RED, grEEn, white, Orange, pink]

Uppercase Strings: [RED, GREEN, WHITE, ORANGE, PINK]
Lowercase Strings: [red, green, white, orange, pink] 

Explanation:

In the above exercises, we have a list of strings containing ("RED", "grEEn", "white", "Orange", "pink"). Using streams. First convert the strings to uppercase by calling the toUpperCase method on each string, and then collect the results into a new list using the collect method. Similarly, convert the strings to lowercase by calling the toLowerCase method on each string. Finally, the uppercase and lowercase lists are printed to the console.

Flowchart:

Flowchart: Java Stream  Exercises - Convert List of Strings to Uppercase or Lowercase using Streams

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Calculate Average of Integers using Streams.
Next: Sum of Even and Odd Numbers in a List using Streams.

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.