如何从列表转换为String - java

时间:2014-03-05 10:05:32

标签: java string list

我需要帮助从我的Jlist jListpersons制作列表,我想将该列表转换为String

List listOfPersonNames = jListpersons.getSelectedValuesList();
String teamName = (String)jListhold.getSelectedValue();
String[] personNamesA = (String[])listOfPersonNames.toArray();

con.createNewTeam(teamName, personNamesA[0], personNamesA[1], personNamesA[2], personNamesA[3]);

4 个答案:

答案 0 :(得分:3)

StringBuilder builder = new StringBuilder();
for(String s : personNamesA ) {
    builder.append(s);
}
System.out.println(builder.toString());
这就是全部。它背后没有任何魔力。

答案 1 :(得分:0)

尝试Arrays.toString

String value = Arrays.toString(personNamesA);
System.out.println(value.substring(1, value.length() - 1));

答案 2 :(得分:0)

List listOfPersonNames = jListpersons.getSelectedValuesList();

// your list of strings
List<String> listOfNameStrings = new ArrayList<String>(listOfPersonNames.size());

for (Object personName: listOfPersonNames) {
    listOfNameStrings.add(personName.toString());
}

// your string from the resulting list
String listString = listOfNameStrings.toString();

如果List.toString()未提供您想要的格式,请添加@Stefan基于StringBuilder的解决方案,将结果列表转换为字符串

答案 3 :(得分:0)

更改这些行:

List listOfPersonNames = jListpersons.getSelectedValuesList();
String[] personNamesA = (String[])listOfPersonNames.toArray();

要:

List<String> listOfPersonNames = jListpersons.getSelectedValuesList();
String[] personNamesA = new String[listOfPersonNames.size()];
personNamesA = listOfPersonNames.toArray(personNamesA );