Core Java

Modifying and Printing List Items Using Java Streams

Lists are fundamental building blocks in Java, holding collections of objects. A task could involve modifying the elements of a list and then printing the modified results. This article explores various strategies for modifying and printing list elements in Java.

1. Sample Data

First, let’s define a sample list of strings:

public class ModifyListExample {

    public static void main(String[] args) {
        List<String> vegetables = Arrays.asList("carrot", "potato", "spinach", "broccoli", "tomato");

    }
}

2. Using List.replaceAll() Method

The List interface provides a method called replaceAll() which allows for in-place modification of all elements in the list based on a specified function. The replaceAll method replaces all occurrences of an element with a new value.

This method is particularly useful when we want to directly modify the elements of an existing list without creating a new list.

2.1 Example Code

In this example, we will use the List.replaceAll() method to modify each string in the list by capitalizing the first letter of each vegetable name.

public class ModifyListExample {

    public static void main(String[] args) {
        
        List<String> vegetables = Arrays.asList("carrot", "potato", "spinach", "broccoli", "tomato");
        
        System.out.println("Original List: " + vegetables);

        // Using List.replaceAll() to capitalize each vegetable name
        vegetables.replaceAll(veg -> capitalizeFirstLetter(veg));

        System.out.println("Modified List: " + vegetables);

    }
    
    // Helper method to capitalize the first letter of a string
    private static String capitalizeFirstLetter(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
}

In this example:

  • We create an ArrayList named vegetables and add vegetable names to it.
  • The replaceAll() method of List is called on vegetables. The lambda expression veg -> capitalizeFirstLetter(veg) is passed to replaceAll() to capitalize the first letter of each vegetable’s name.
  • We define the capitalizeFirstLetter method – a helper function used within the lambda expression to capitalize the first letter of a given string.

When we run the above code, we will see the following output:

Original List: [carrot, potato, spinach, broccoli, tomato]
Modified List: [Carrot, Potato, Spinach, Broccoli, Tomato]

3. Using forEach with Stream

Java Streams provide an efficient and expressive method for handling collections. We can modify and print each element in the list by using the forEach or forEachOrdered method with a stream. This method takes a lambda expression that specifies what action to perform on each element.

Example:

public class StreamExample {

    public static void main(String[] args) {

        List<String> vegetables = Arrays.asList("carrot", "potato", "spinach", "broccoli", "tomato");

        vegetables.stream()
                .map(vegetable -> vegetable.toUpperCase()) // Modify each element (convert to uppercase)
                .forEachOrdered(System.out::println);    // Print each modified element
    }
}

In this example:

  • .map(vegetable -> vegetable.toUpperCase()) transforms each element in the stream to its uppercase version using the toUpperCase() method.
  • .forEachOrdered(System.out::println) prints each modified element to the console.

The output from running the above code is:

Fig 1: Output from the example using Java stream to print list print elements after an update
Fig 1: Output from the example using Java stream to print list print elements after an update

4. Collecting Modified Elements

An alternative method is to collect the modified elements into a new list and subsequently print them.

public class NewModifiedListExample {

    public static void main(String[] args) {

        List<String> vegetables = Arrays.asList("carrot", "potato", "spinach", "broccoli", "tomato");

        List<String> modified = vegetables.stream()
                .map(vegetable -> vegetable.substring(0, 1).toUpperCase() + vegetable.substring(1))
                .collect(Collectors.toList());

        modified.forEach(System.out::println);
    }
}

In this example:

  • .map(vegetable -> vegetable.substring(0, 1).toUpperCase() + vegetable.substring(1)) modifies each element by capitalizing the first letter.
  • .collect(Collectors.toList()) collects the modified elements into a new list.

When we run the above code, we will get the following output:

Carrot
Potato
Spinach
Broccoli
Tomato

4.1 Filtering and Printing Specific Elements

We can also filter elements based on certain conditions and then print the results.

Example:

        vegetables.stream()
                .filter(vegetable -> vegetable.length() > 6) // Filter elements based on length
                .map(vegetable -> vegetable.substring(0, 1).toUpperCase() + vegetable.substring(1))
                .forEach(System.out::println);

In this example:

  • .filter(vegetable -> vegetable.length() > 6) filters elements based on a condition (word length > 6).
  • The subsequent .map(...) and .forEach(...) operations modify and print the filtered elements.

The output is:

Spinach
Broccoli

5. Conclusion

In this article, we have covered several methods for modifying and printing List Items in Java. We explored:

  • Using List.replaceAll() method for element modification.
  • Using forEach to directly modify and print elements.
  • Collecting modified elements into a new list.
  • Filtering elements before modification.

In conclusion, leveraging Java Streams and related methods like List.replaceAll() offers us powerful tools to efficiently modify and print list items using Java.

6. Download the Source Code

This was an article on how to list, update and print elements in Java using Stream.

Download
You can download the full source code of this example here: List, update and print elements in Java using Stream

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button