Convert a for loop to concat String into a lambda expression

后端 未结 5 1693
予麋鹿
予麋鹿 2021-02-03 22:37

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

5条回答
  •  执笔经年
    2021-02-03 23:16

    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.

提交回复
热议问题