首页 \ 问答 \ 将列表对象中的字符串转换为逗号分隔(Convert string in list objects to comma separated)

将列表对象中的字符串转换为逗号分隔(Convert string in list objects to comma separated)

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

例如,

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

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

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


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.


原文:https://stackoverflow.com/questions/18743016
更新时间:2020-10-25 08:10

最满意答案

覆盖Employee类中的toString()方法

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

Override the toString() method in the Employee class

public String toString() {
   return name;
}

Then, print the list:

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

This is not that sophisticated way to print it, but I doesn't involve the usage of third-party libraries.

If you'd like to use third party libraries, here are several way you can print the list.

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

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

相关问答

更多

将列表转换为逗号分隔的字符串(Convert List into Comma-Separated String)

请享用! Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 })); String.Join将以列表作为第二个参数,并使用作为第一个参数传递的字符串将所有元素连接到一个单个字符串中。 Enjoy! Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 })); First Parameter: "," Second Parameter: ...

如何将逗号分隔的字符串转换为Python中的列表?(How to convert comma-delimited string to list in Python?)

您可以使用str.split方法。 >>> my_string = 'A,B,C,D,E' >>> my_list = my_string.split(",") >>> print my_list ['A', 'B', 'C', 'D', 'E'] 如果你想把它转换成一个元组,就可以了 >>> print tuple(my_list) ('A', 'B', 'C', 'D', 'E') 如果您想追加到列表中,请尝试: >>> my_list.append('F') >>> print my_l ...

如何将字符串数组转换为逗号分隔的字符串?(How to convert an array of strings into a comma separated string?)

["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"' ["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'

将`List `转换为逗号分隔的字符串(Convert `List` to comma-separated string)

在.NET 4中,您不需要ToArray()调用 - string.Join被重载以接受IEnumerable<T>或只是IEnumerable<string> 。 在.NET 4之前有更有效的方法来做,但是你真的需要它们吗? 这实际上是你代码中的瓶颈吗? 您可以遍历列表,找出最终的大小,分配一个正确大小的StringBuilder ,然后自己进行加入。 这将避免额外的数组被建立的原因很小 - 但它不会节省很多时间,这将是更多的代码。 In .NET 4 you don't need the To ...

将列表转换为逗号分隔的字符串(Converting a List to a comma separated string)

List<int> list = ...; string.Join(",", list.Select(n => n.ToString()).ToArray()) List<int> list = ...; string.Join(",", list.Select(n => n.ToString()).ToArray())

如何将逗号分隔的字符串转换为ArrayList?(How to convert comma-separated String to ArrayList?)

将逗号分隔的字符串转换为列表 List<String> items = Arrays.asList(str.split("\\s*,\\s*")); 上述代码将字符串分隔在一个定义为: zero or more whitespace, a literal comma, zero or more whitespace的定界符上zero or more whitespace, a literal comma, zero or more whitespace将把这些单词放入列表中,并在单词和逗号之间折 ...

如何将逗号分隔的字符串或/ n分隔的字符串转换为jquery中的列表?(How to convert the comma separated string or /n separated string into list in jquery?)

如果基于逗号的拆分只给出一个元素,请尝试新的换行: var str = $("#textValue").val(); var array = new Array(); array = emailString.split(','); if (array.length == 1) { array = emailString.split('\n'); } If the comma based split gave only one element, try a new line spl ...

将逗号分隔的字符串转换为最后一个逗号的列表(Convert a comma separated string to list which has a comma at the last)

将分割线更改为: String [] items = s.split(",", -1); 它应该像你期望的那样。 这是有限制的版本。 检查参考 。 Change the split line to: String [] items = s.split(",", -1); and it should do as you expect. This is the version with the limit. Check the reference.

将逗号分隔的字符串转换为int列表并进行验证(Convert comma separated string to int list and validate)

如果你想验证只有有效的int将达到Select use int.TryParse : int num; var result = model.Categories.Split(',') .Where(i => int.TryParse(i, out num)) .Select(int.Parse).ToList(); 如果使用C#7.0那么可以只是: var result = model.Categories.Split(' ...

将列表对象中的字符串转换为逗号分隔(Convert string in list objects to comma separated)

覆盖Employee类中的toString()方法 public String toString() { return name; } 然后,打印列表: String listToString = empList.toString(); System.out.println(listToString.substring(1, listToString.length() - 1)); 这不是那种复杂的打印方式,但我不涉及使用第三方库。 如果您想使用第三方库,可以通过以下几种方式打印列表。 ...

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)