Is it possible to make library classes comparable without extending them?
import org.json.JSONObject;
LinkedList<JSONObject> list = getListFromFunction();
TreeSet<JSONObject> treeSet = new TreeSet<JSONObject>(list);
Making a TreeSet
here is not possible as JSONObject
is not comparable. How can I "attach" a custom comparator to JSONObject
?
(There is a unique property, say "_some_id" to compare with)
We can use Comparator in such a case and handle the scenario. Please refer the below example.
Main Class
public class ComparatorTest{
public static void main(String[] ar) {
// System.out.println(new Sample().stringTimes("vivek", 5));
JSONObject emp1 = new JSONObject();
JSONObject emp2 = new JSONObject();
try {
emp1.put("department", "IT");
emp1.put("name", "bvivek");
emp1.put("id", 1);
emp2.put("department", "IT");
emp2.put("name", "avikash");
emp2.put("id", 2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<JSONObject> employess = new ArrayList<JSONObject>();
employess.add(emp1);//add to list
employess.add(emp2);//add to list
System.out.println(employess);//unsorted, as is
Collections.sort(employess, new JSONComparator("name"));
System.out.println(employess);//sorted as per the field
//using treeSet
TreeSet<JSONObject> jsonInTree = new TreeSet<JSONObject>(new JSONComparator("id"));
jsonInTree.addAll(employess);
System.out.println(jsonInTree);//using the tree implementation
}
}
JSONComparator
class JSONComparator implements Comparator<JSONObject> {
private String fieldToCompare;
public JSONComparator(String fieldToCompare) {
this.fieldToCompare = fieldToCompare;
}
@Override
public int compare(JSONObject o1, JSONObject o2) {
String id1 = "";
String id2 = "";
try {
id1 = o1.getString(this.fieldToCompare);
id2 = o2.getString(this.fieldToCompare);
} catch (JSONException e) {
}
return id1.compareTo(id2);
}
}