Join strings with different last delimiter

前端 未结 7 1184
感情败类
感情败类 2021-01-04 12:04

Using stream.collect(Collectors.joining(\", \")) I can easily join all the strings of my stream delimited by a comma. A possible result would be \"a, b, c

7条回答
  •  旧巷少年郎
    2021-01-04 12:51

    If you're fine with "a, b, and c", then it's possible to use mapLast method of my StreamEx library which extends standard Stream API with additional operations:

    String result = StreamEx.of("a", "b", "c")
                            .mapLast("and "::concat)
                            .joining(", "); // "a, b, and c"
    

    The mapLast method applies given mapping to the last stream element keeping others unchanged. I even have similar unit-test.

提交回复
热议问题