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
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 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.