[英]Convert objects in ArrayList to String
我正在尝试从已放置在 ArrayList 中的对象返回连接的字符串。
public String displayProperties() {
StringBuilder propertyList = new StringBuilder();
properties.forEach(propertyList::append);
String e = propertyList.toString();
return e;
}
当我返回 e. 我得到一个对象引用。
属性定义为:
List<House> properties = new ArrayList <House>();
我不确定您是否会像人群建议的那样对覆盖toString()
感到满意。 但如果你想这样做,很简单,让我们假设:
class House{
final String road;
final int houseNumber;
House(String road, int houseNumber) {
this.road = road;
this.houseNumber = houseNumber;
}
@Override
public String toString() {
return "House{" +
"road='" + road + '\'' +
", houseNumber=" + houseNumber +
'}';
}
}
这里被覆盖的是类Object
toString()
方法,它是所有事物的根(在 Java 编程语言中)。 但请注意,如果那是House
的唯一 String 表示形式,那么就业务需求而言,您可能会遇到麻烦。 或者,当需要第二次代表时,您最近会遇到麻烦。
例如,如果您想从House
打印更合理的内容,您可以这样做。 ( \\r\\n
... 回车/换行):
List<House> houses = new ArrayList<House>();
String ad = houses.stream()
.map(h -> String.format("We're excessively proud to present you house nr %d at %s road\r\n", h.houseNumber, h.road))
.reduce("", (i, j) -> i + j);
StringBuilder 版本将是这样的:
StringBuilder sb = new StringBuilder();
for(House h: houses)
{
sb.append(String.format("We're insanely proud to present you house nr %d at %s road\r\n", h.houseNumber, h.road));
}
String ad = sb.toString();
我试图从已放置在ArrayList中的对象返回串联的字符串。
public String displayProperties() {
StringBuilder propertyList = new StringBuilder();
properties.forEach(propertyList::append);
String e = propertyList.toString();
return e;
}
当我返回e。 我得到一个对象引用。
属性定义为:
List<House> properties = new ArrayList <House>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.