Skip to content
Advertisement

Convert a for loop to concat String into a lambda expression

I have the following for loop which iterates through a list of strings and stores the first character of each word in a StringBuilder. I would like to know how can I transform this to a lambda expression

StringBuilder chars = new StringBuilder();
for (String l : list) {
    chars.append(l.charAt(0));
}  

Advertisement

Answer

Assuming you call toString() on the StringBuilder afterwards, I think you’re just looking for Collectors.joining(), after mapping each string to a single-character substring:

String result = list
    .stream()
    .map(s -> s.substring(0, 1))
    .collect(Collectors.joining());

Sample code:

import java.util.*;
import java.util.stream.*;

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("foo");
        list.add("bar");
        list.add("baz");
        String result = list
            .stream()
            .map(s -> s.substring(0, 1))
            .collect(Collectors.joining());
        System.out.println(result); // fbb
    }
}

Note the use of substring instead of charAt, so we still have a stream of strings to work with.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement