从Java中的列表构建定界字符串的最佳方法 [英] Best way to build a delimited string from a list in java

查看:127
本文介绍了从Java中的列表构建定界字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,每个对象都有一个字符串属性.例如,我有一个List<Person>,每个Person都有一个firstName属性.我想构建一个逗号分隔的加引号的字符串,如下所示:

I have a list of objects, and each object has a string property. For example, I have a List<Person> and each Person has a firstName property. I want to build a comma-delimited, quoted string that looks like this:

'James', 'Lily', 'Michael'

考虑到Java似乎没有join方法(而且,这比简单的定界字符串要复杂得多),最简单的方法是什么?我一直在尝试编写一些代码,但是我的代码变得非常凌乱,可以使用一些新的输入.

Considering that java doesn't seem to have a join method (and besides, this is a bit more complicated than a simple delimited string), what's the most straightforward way to do this? I've been trying to code this for a bit but my code's gotten very messy and I could use some fresh input.

推荐答案

如果您想简单手动进行操作,则可以执行以下操作:

If you want to do it simply and manually, you could do something like this:

String mystr = "";
for(int i = 0; i < personlist.size(); i++) {
  mystr += "\'" + personlist.get(i).firstName + "\'";
  if(i != (personlist.size() - 1)) {
    mystr += ", ";
  }
}

现在,mystr包含您的列表.请注意,仅当我们不对列表中的最后一个元素(索引为personlist.size()-1)进行操作时,才会添加逗号.

Now mystr contains your list. Note that the comma is only added if we are not acting on the last element in the list (with index personlist.size() - 1).

当然,有更多优雅/有效的方法可以完成此操作,但我认为这是最清晰的方法.

Of course, there are more elegant/efficient methods to accomplish this, but this one is, in my opinion, the clearest.

这篇关于从Java中的列表构建定界字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆