Convert a for loop to concat String into a lambda expression

后端 未结 5 1804
予麋鹿
予麋鹿 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:18

    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.

提交回复
热议问题