/** * Replaces the first matching element. * @param e1 original * @param e2 replacement * @return true if the element was replaced. */ public boolean replace(JsonElement e1, JsonElement e2) { int index = indexOf(e1); if(index>=0) { set(index, e2); return true; } else { return false; } }
/** * Convenient replace method that allows you to replace an object based on field equality for a specified field. * Useful if you have an id field in your objects. Note, the array may contain non objects as well or objects * without the specified field. Those elements won't be replaced of course. * * @param e1 object you want replaced; must have a value at the specified path * @param e2 replacement * @param path path * @return true if something was replaced. */ public boolean replaceObject(JsonObject e1, JsonObject e2, String...path) { JsonElement compareElement = e1.get(path); if(compareElement == null) { throw new IllegalArgumentException("specified path may not be null in object " + StringUtils.join(path)); } int i=0; for(JsonElement e: this) { if(e.isObject()) { JsonElement fieldValue = e.asObject().get(path); if(compareElement.equals(fieldValue)) { set(i,e2); return true; } } i++; } return false; }
/** * GeoJson specifies the order of coordinates as x,y or in geo terms longitude followed by latitude. * Most data sources stick to latitude, longitude though. This function, swaps the two for any dimension array. * * * @param array 2d array with latitude, longitude pairs * @return swapped array 2d array with longitude, latitude pairs */ public static @Nonnull JsonArray swapLatLon(@Nonnull JsonArray array) { if(array.isNotEmpty() && array.first().isArray()) { for(JsonElement e: array) { swapLatLon(e.asArray()); } } else { if(array.size() < 2) { throw new IllegalArgumentException("need at least two coordinates"); } JsonElement first = array.get(0); JsonElement second = array.get(1); array.set(0, second); array.set(1, first); } return array; }