1

I have an arraylist of objects, where one of the instance variables in the object is string. I would like to convert the string variables in the object list into a single comma-separated string.

For example,

I have an object employee as below.

public class Employee {

    private String name;
    private int age;
}

Consider a list of employees,

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);

Expected output (Type : String):

Emp 1,Emp 2

I know it can be done through looping. But I'm looking for some sophisticated ways to do it and keep the code simpler.

4

4 回答 4

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, ", ");
于 2013-09-11T13:48:33.473 回答
0

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

  • 实现你自己的toString()

    public String toString() { return name; }
    
  • toString()在您的调用方法java.util.List

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

    String s = empList.toString();
    s = s.substring(1, s.length()-1);
    
于 2013-09-11T13:50:01.627 回答
0

如果您想要一种真正干净的方式来执行此操作,请使用 Java 8 中的函数文字。否则,

在员工类中:

public String toString() { return name; }

打印出列表,去掉方括号

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

于 2013-09-11T13:54:39.873 回答
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
于 2013-09-11T13:54:49.420 回答