将列表对象中的字符串转换为逗号分隔

时间:2013-09-11 13:46:54

标签: java

我有一个对象的arraylist,其中对象中的一个实例变量是string。 我想将对象列表中的字符串变量转换为单个逗号分隔的字符串。

例如,

我有一名对象员工,如下所示。

public class Employee {

    private String name;
    private int age;
}

考虑员工名单,

List<Employee> empList = new ArrayList<Employee>
Employee emp1 = new Employee ("Emp 1",25);
Employee emp2 = new Employee ("Emp 2",25);
empList.add(emp1);
empList.add(emp2);

预期输出(类型:字符串):

Emp 1,Emp 2

我知道可以通过循环来完成。但我正在寻找一些复杂的方法来实现它并使代码更简单。

4 个答案:

答案 0 :(得分:4)

覆盖toString()

中的Employee方法
public String toString() {
   return name;
}

然后,打印清单:

String listToString = empList.toString();
System.out.println(listToString.substring(1, listToString.length() - 1));

这不是复杂的打印方式,但我不涉及使用第三方库。

如果您想使用第三方库,可以通过以下几种方式打印列表。

// Using Guava
String guavaVersion = Joiner.on(", ").join(items);

// Using Commons / Lang
String commonsLangVersion = StringUtils.join(items, ", ");

答案 1 :(得分:0)

  

我想将对象列表中的字符串变量转换为单个逗号分隔的字符串。

  • 实施您自己的toString()

    public String toString() { return name; }
    
  • toString()上调用java.util.List方法:

    empList.toString();
    
  • 摆脱'['']'

    String s = empList.toString();
    s = s.substring(1, s.length()-1);
    

答案 2 :(得分:0)

如果您想要一种真正干净的方法,请在Java 8中使用函数文字。否则,

在员工类中:

public String toString() { return name; }

打印清单,删除方括号

list.toString().replaceAll("\\[(.*)\\]", "$1");

答案 3 :(得分:0)

没有循环,使用list.toString()

public class Employee {

     public Employee(String string, int i) {
        this.age=i;
        this.name=string;
    }
    private String name;
     private int age;

     @Override
     public String toString() {
           return name + " " + age;
        }

   public static void main(String[] args) {
       List<Employee> empList = new ArrayList<Employee>();
         Employee emp1 = new Employee ("Emp 1",25);
         Employee emp2 = new Employee ("Emp 2",25);
         empList.add(emp1);
         empList.add(emp2);
         System.out.println(empList.toString().
                       substring(1,empList.toString().length()-1));
}
}

打印

Emp 1 25, Emp 2 25
相关问题