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.comparingIntYou should be able to do the following:
getIntCheck the API of the
JSONObjectto see if there is angetIntmethod or similar on it, then you should be able to use that directly instead of wrapping invalueOfcalls, such as:Return type of
.getAlternatively, 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
StringIf you are always getting
Stringsas a result fromobj.get, then you should be able to useInteger.valueOfdirectly, instead of also callingString.valueOfDepending on the API, you still might need to typecase to
String