Convert a for loop to concat String into a lambda expression
Without creating many intermediate String objects you can do it like this:
StringBuilder sb = list.stream()
.mapToInt(l -> l.codePointAt(0))
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append);
Note that using codePointAt
is much better than charAt
as if your string starts with surrogate pair, using charAt
you may have an unpredictable result.
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.
Tons of ways to do this - the most simple option: stick to adding to a StringBuilder
and do this:
StringBuilder chars = new StringBuilder();
list.forEach(l -> chars.append(l.charAt(0)));