Home  >  Q&A  >  body text

java - Stream 元素是字符串,用逗号拼接

Stream.of("1","2","3","4")这个是输入
我想得到1,2,3,4的输出,怎么写?

天蓬老师天蓬老师2712 days ago765

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:09:53

    Use reduce

    Stream.of("1","2","3","4").reduce((a,b) -> a +"," +b))

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:09:53

    If you are like me and don’t understand what reduce does

    String.join(",", stringStream.collect(Collectors.toList()));

    It’s a bit difficult to change your thinking

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:09:53

    Stream.of(1, 2, 3, 4).reduce(new StringBuilder(), (sb, s) -> sb.append(s).append(','), StringBuilder::append).toString();

    reply
    0
  • Cancelreply