Java: convert List to a String

前端 未结 22 2634
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  走了就别回头了
    2020-11-22 01:56

    All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.

    You can do the simple join case with

    Joiner.on(" and ").join(names)
    

    but also easily deal with nulls:

    Joiner.on(" and ").skipNulls().join(names);
    

    or

    Joiner.on(" and ").useForNull("[unknown]").join(names);
    

    and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:

    Map ages = .....;
    String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
    // Outputs:
    // Bill is 25, Joe is 30, Betty is 35
    

    which is extremely useful for debugging etc.

提交回复
热议问题