I have been trying to sort a JSONArray using Java 8's Stream api. However I guess I couldn't get the type casting done right.
The far I could get is the following piece of code.,
String objects = "[\n" +
" {\n" +
" \"lat\": \"-16.408545\",\n" +
" \"lon\": \"-71.539105\",\n" +
" \"type\": \"0\",\n" +
" \"distance\": \"0.54\"\n" +
" },\n" +
" {\n" +
" \"lat\": \"-16.4244317845\",\n" +
" \"lon\": \"-71.52562186\",\n" +
" \"type\": \"1\",\n" +
" \"distance\": \"1.87\"\n" +
" },\n" +
" {\n" +
" \"lat\": \"-16.4244317845\",\n" +
" \"lon\": \"-71.52562186\",\n" +
" \"type\": \"1\",\n" +
" \"distance\": \"0.22\"\n" +
" }\n" +
" {\n" +
" \"lat\": \"-16.4244317845\",\n" +
" \"lon\": \"-71.52562186\",\n" +
" \"type\": \"1\",\n" +
" \"distance\": \"2.69\"\n" +
" }\n" +
"]";
JSONArray objectsArray = (JSONArray) new JSONParser().parse(objects);
objectsArray.stream().sorted(Comparator.comparing(a -> ((JSONObject) a).get("distance")));
I get the following error.
Error:(42, 62) java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Object
upper bound(s): java.lang.Comparable<? super java.lang.Object>
I also referred this question. But I feel that this could be done in an easier way with streams. Any Ideas? I use the following dependency for JSONObject
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>