What's the best way to build a string of delimited items in Java?

前端 未结 30 2485
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i

30条回答
  •  一生所求
    2020-11-22 06:21

    So a couple of things you might do to get the feel that it seems like you're looking for:

    1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)

    2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.

    Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.

    To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.

提交回复
热议问题