0

i've a List<Polygon> polygons, where Polygon represents the geojson concept of polygon. In the class Polygon i defined a method toGeojson() that returns a string containing the geojson representation. 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. Is there a way to call toGeojson() on a List just as you'd do with toString()?

Cilla
  • 419
  • 5
  • 16
  • Possible duplicate of [Best way to convert an ArrayList to a string](http://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string) – Anton Balaniuc May 10 '17 at 09:48

3 Answers3

4

Not sure if that answers your question, but you can use Stream api for that thing.

String result = polygons.stream()
        .map(Polygon::toGeojson)
        .collect(Collectors.joining(","));

There is no direct way to override behaviour of List.toString().

updated There is Collectors#joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) method which accepts suffix and prefix. Using this method we can make our output look exactly like List.toSting with square brackets.

String result = polygons.stream()
            .map(Polygon::toGeojson)
            .collect(Collectors.joining(",", "[", "]")); // ["x","y"]
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
0

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. In that case I don't see a better way than a loop, but avoid String concatenation inside loops. Use StringBuilder instead which has much better performance.

StringBuilder result = new StringBuilder();
for (Polygon p: polygons) {
   result.append(p.toGeojson());
}
Community
  • 1
  • 1
0

Your solution is the best, i think... In Java there is no faster solution and the Array.toString method works the same way.

qry
  • 457
  • 3
  • 11