[英]Java list visualization
i've a List<Polygon> polygons
, where Polygon represents the geojson concept of polygon. 我有一个
List<Polygon> polygons
polygons,其中Polygon代表多边形的geojson概念。 In the class Polygon i defined a method toGeojson()
that returns a string containing the geojson representation. 在类Polygon中,我定义了一个
toGeojson()
方法,该方法返回包含geojson表示形式的字符串。 I'd like to print all the list in a compact way instead of doing this: 我想以紧凑的方式打印所有列表,而不是这样做:
String result = '';
for(Polygon p: polygons)
result += p.toGeojson();
I could do result = p.toString()
but i cannot use toString()
method because i use it for an other thing. 我可以做
result = p.toString()
但我不能使用toString()
方法,因为我将它用于另一件事。 Is there a way to call toGeojson()
on a List just as you'd do with toString()
? 有没有办法像使用
toString()
一样在列表上调用toGeojson()
toString()
吗?
Not sure if that answers your question, but you can use Stream
api for that thing. 不知道这是否能回答您的问题,但是您可以使用
Stream
api进行处理。
String result = polygons.stream()
.map(Polygon::toGeojson)
.collect(Collectors.joining(","));
There is no direct way to override behaviour of List.toString()
. 没有直接方法可以重写
List.toString()
行为。
updated There is Collectors#joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) method which accepts suffix and prefix. 更新了有Collectors#joining(CharSequence分隔符,CharSequence前缀,CharSequence后缀)方法,该方法接受后缀和前缀。 Using this method we can make our output look exactly like
List.toSting
with square brackets. 使用此方法,我们可以使输出看起来完全像带有方括号的
List.toSting
。
String result = polygons.stream()
.map(Polygon::toGeojson)
.collect(Collectors.joining(",", "[", "]")); // ["x","y"]
I am not sure I understand what you want, but I guess you are looking for a way to print the geoJson representation of each Polygon
contained in your List. 我不确定我了解您想要什么,但是我想您正在寻找一种方法来打印列表中包含的每个
Polygon
的geoJson表示形式。 In that case I don't see a better way than a loop, but avoid String
concatenation inside loops. 在那种情况下,我没有比循环更好的方法了,但是要避免在循环内部使用
String
串联。 Use StringBuilder
instead which has much better performance . 使用
StringBuilder
代替它具有更好的性能 。
StringBuilder result = new StringBuilder();
for (Polygon p: polygons) {
result.append(p.toGeojson());
}
我认为,您的解决方案是最好的...在Java中,没有更快的解决方案,并且Array.toString方法的工作方式相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.