Get startedGet started for free

Cleaning strings

You've extracted product names from your electronics inventory into a list of strings. The product names are messy, and some have leading and trailing spaces, non-letters, multiple spaces, or mixed cases. Clean the product names from your inventory.

This exercise is part of the course

Cleaning Data in Java

View Course

Exercise instructions

  • Remove leading and trailing spaces from each product name.
  • Replace multiple spaces with a single space in the products.
  • Convert all product names to lowercase.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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

public class ProductDataExample {
	public static void main(String[] args) {
    	String[] messyProducts = {
            "Laptop ", "SMARTPHONE", 
            "Monitor *(Display)*", "   Bluetooth    Speaker   "
        };

        Arrays.stream(messyProducts)
              // Remove leading and trailing spaces
              .map(s -> s.____()
                     .replaceAll("[^a-zA-Z\\s]", "")
                     // Replace multiple spaces with a single space
                     .replaceAll("____", " ")
                     // Convert to lowercase
                     .____())
              .forEach(System.out::println);
    }
}
Edit and Run Code