Using Comparator.comparingInt
You should be able to do the following:
Comparator<JSONObject> comparator =
Comparator.comparingInt(obj -> Integer.valueOf(String.valueOf(obj.get(field))))
.reversed();
getInt
Check the API of the JSONObject
to see if there is an getInt
method or similar on it, then you should be able to use that directly instead of wrapping in valueOf
calls, such as:
Comparator<JSONObject> comparator = Comparator.<JSONObject>comparingInt(obj -> obj.getInt(field))
.reversed();
Return type of .get
Alternatively, you should investigate what type your obj.get(field)
returns. If you are lucky, it can be as simply as a typecast:
Comparator<JSONObject> comparator =
Comparator.<JSONObject>comparingInt(obj -> (Integer) obj.get(field))
.reversed();
Return type is String
If you are always getting Strings
as a result from obj.get
, then you should be able to use Integer.valueOf
directly, instead of also calling String.valueOf
Comparator<JSONObject> comparator =
Comparator.<JSONObject>comparingInt(obj -> Integer.valueOf(obj.get(field)))
.reversed();
Depending on the API, you still might need to typecase to String
Comparator<JSONObject> comparator =
Comparator.<JSONObject>comparingInt(obj -> Integer.valueOf((String) obj.get(field)))
.reversed();