这是我编写的用于将List转换为表示geojson FeatureCollection的ObjectNode的函数。
public class ToObjectNodeFunction implements Function<List<JsonNode>, ObjectNode> {
@Override
public ObjectNode apply(List<JsonNode> list) {
/*
* toGeojson() method return an ObjectNode representing that particular geometry
*/
List<ObjectNode> objectNodes = list.parallelStream()
.map(jsonNode -> {
String id = jsonNode.get("id").asText();
JsonNode tags = jsonNode.get("tags");
switch (jsonNode.get("type").asText()) {
case "node":
return new Point(jsonNode.get("lat").asDouble(), jsonNode.get("lon").asDouble(), id, tags).toGeojson();
case "way":
ArrayList<Point> points = new ArrayList<>();
JsonNode nodeList = jsonNode.get("geometry");
for (int j = 0; j < nodeList.size(); j++) {
JsonNode wayNode = nodeList.get(j);
points.add(j, new Point(wayNode.get("lat").asDouble(), wayNode.get("lon").asDouble()));
}
if (Polygon.isPolygon(points, tags)) {
return new Polygon(points, id, tags).toGeojson();
} else {
return new LineString(points, id, tags).toGeojson();
}
default:
Iterator<JsonNode> iterator = jsonNode.get("members").getElements();
List<List<Point>> rings = new ArrayList<>();
List<Point> ring;
while (iterator.hasNext()) {
JsonNode member = iterator.next();
JsonNode geometry = member.get("geometry");
ring = new ArrayList<>();
for (int ringIndex = 0; ringIndex < geometry.size(); ringIndex++) {
JsonNode coordinates = geometry.get(ringIndex);
ring.add(new Point(coordinates.get("lat").asDouble(), coordinates.get("lon").asDouble()));
}
rings.add(ring);
}
return new Multipolygon(Polygon.buildPolygons(rings), id, tags).toGeojson();
}
})
.collect(toList());
ObjectNode featureCollection = NewFeatureCollection.createNewFeatureCollection();
ArrayNode features = featureCollection.putArray("features");
objectNodes.stream().forEach((objectNode) -> features.add(objectNode));
return featureCollection;
}
}
这种方法应该尽可能快,我想知道是否有更好的方法来实现结果。特别是,我想避免必须创建ObjectNode列表,然后必须迭代以创建表示要素集合的ObjectNode。如何直接创建要素集?