List First Names

Extracting the first name from a list of full-name strings is a map() transformation that splits each string on whitespace and takes the first token.

Key Points: • map(name -> name.split(" ")[0]) applies a lambda to every element, returning the first word of each name. • String.split(" ") returns an array, so indexing [0] grabs the first name portion specifically. • This approach assumes a simple "First Last" format; names with extra whitespace or different formats need more robust parsing. • Because map() is one-to-one, the resulting stream has exactly as many elements as the input. • For more complex name parsing, a dedicated regex or a proper name-parsing library would be more robust than a naive split.

Example: Given the list ["Alice Johnson", "Bob Harris", "Charlie Lou"], mapping with name -> name.split(" ")[0] produces ["Alice", "Bob", "Charlie"].

Code Example:

List<String> fullNames = Arrays.asList(
        "Alice Johnson", "Bob Harris", "Charlie Lou");

List<String> firstNames = fullNames.stream()
        .map(name -> name.split(" ")[0])
        .collect(Collectors.toList());

Interview Tip: A concise interview answer is:

"I map each full name string by splitting on a space and taking index zero of the resulting array, then collect the results into a list of first names. It's a simple approach that assumes a straightforward two-part name format."