Java 8 流收集

约瑟夫·莫夫

我怎样才能在 Java 8 中做到这一点。我有一个ArrayList<String>例子:

List<String> places = Arrays.asList("Apple", "Banana", "Coconut");

我想将它存储在一个字符串中

  • 单项必须用单引号括起来
  • 逗号分隔
  • 括在括号中

结果: ['Apple', 'Banana', 'Coconut']

绝地求生

也许这个:

String string = places.stream().collect(Collectors.joining("', '", "['", "']"));

更新

正如另一个用户让我注意到的,要处理空列表,必须重构代码:

String string = places
                 .stream()
                 .map(e -> "'" + e + "'")
                 .collect(Collectors.joining(", ", "[", "]"));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章