CommencerCommencer gratuitement

Processing usernames for display

In a user management system, we need to display usernames stored in a database. Using Streams and .forEach(), we can efficiently process and print each username without using traditional loops.

Cet exercice fait partie du cours

Input/Output and Streams in Java

Afficher le cours

Instructions

  • Convert the usernames list into a Stream object.
  • Print each element in the stream using a lambda expression.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Stream;

public class UserDisplay {
    public static void main(String[] args) {
        List usernames = new ArrayList<>();
        usernames.add("Alice123");
        usernames.add("BobTheCoder");
        usernames.add("CharlieDev");
        usernames.add("David99");

        // Convert list to Stream
        Stream stream = usernames.____();
        // Print each username
        stream.____(name -> System.out.println("User: " + name));
    }
}
Modifier et exécuter le code