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()?

1

3 Answers 3

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"]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.