Any better way to write this comparator?
Comparator<JSONObject> comparator = (op1,op2) -> {
Integer id1 = Integer.valueOf(String.valueOf(op1.get(field)));
Integer id2 = Integer.valueOf(String.valueOf(op2.get(field)));
return id2.compareTo(id1);
};
Is it possible to avoid the two valueOf
?
Using
Comparator.comparingInt
You should be able to do the following:
getInt
Check the API of the
JSONObject
to see if there is angetInt
method or similar on it, then you should be able to use that directly instead of wrapping invalueOf
calls, such as: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:Return type is
String
If you are always getting
Strings
as a result fromobj.get
, then you should be able to useInteger.valueOf
directly, instead of also callingString.valueOf
Depending on the API, you still might need to typecase to
String