The object has 3 fields - date of purchase, price and quality. How to implement 3 sorting by appropriate fields via compareTo()
?
1 answer
An example of implementation using reflection and the Comparator
. Can be adapted for use with compareTo()
. Full source on ideone
class Ideone { ... // http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts-based-on-name private static class MyObjectComparator implements Comparator<Object> { private String getter; public MyObjectComparator(String field) { this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1); } @Override public int compare(Object o1, Object o2) { try { if (o1 != null && o2 != null) { o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]); o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]); } } catch (Exception e) { throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e); } return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2)); } } public static void main (String[] args) throws java.lang.Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); List<MyObject> objs = new ArrayList<>(); objs.add(new MyObject(sdf.parse("21/12/2015"), 1234, 2)); objs.add(new MyObject(sdf.parse("12/01/2016"), 134, 4)); objs.add(new MyObject(sdf.parse("01/01/2012"), 3244, 1)); System.out.println("Сортировка по качеству:"); Collections.sort(objs, new MyObjectComparator("quality")); System.out.println(objs); System.out.println("Сортировка по цене:"); Collections.sort(objs, new MyObjectComparator("price")); System.out.println(objs); System.out.println("Сортировка по дате:"); Collections.sort(objs, new MyObjectComparator("date")); System.out.println(objs); } }
Result of performance:
Sort by quality:
[MyObject [01/01/2012, 3244, 1], MyObject [21/12/2015, 1234, 2], MyObject [12/01/2016, 134, 4]]
Sort by price:
[MyObject [12/01/2016, 134, 4], MyObject [12/21/2015, 1234, 2], MyObject [01/01/2012, 3244, 1]]
Sort by date:
[MyObject [01/01/2012, 3244, 1], MyObject [21/12/2015, 1234, 2], MyObject [12/01/2016, 134, 4]]
|
Comparable
interface? Or is theComparator
suitable? - Pavel Parshin