Java – convert a for loop to a concat string of a lambda expression
•
Java
I have the following for loop to traverse a string list and store the first character of each word in StringBuilder I want to know how to convert it to a lambda expression
StringBuilder chars = new StringBuilder(); for (String l : list) { chars.append(l.charAt(0)); }
Solution
Assuming you call toString () after StringBuilder, I think you are looking for Collectors. after mapping each string to a single character substring. joining():
String result = list .stream() .map(s -> s.substring(0,1)) .collect(Collectors.joining());
Example 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 that substrings are used instead of charat, so we still have a string to deal with
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码