Search code examples
javacollectionscomparatorsortedmap

Sorting Map<ArrayList, List<Entity>> by Key - ArrayList is set of Dates


Below is code for the Comparator, however after SortedMap.putAll(), the SortedMap has lesser number of Map Entries as compared to the source Map.

Could anyone please help?

Comparator<ArrayList> arrayListComparer = new Comparator<ArrayList>() {
                @Override
                public int compare(ArrayList arrA, ArrayList arrB) {
                    DateFormat formatter = new SimpleDateFormat("MMM-yyyy");
                    Date dateA = new Date();
                    Date dateB = new Date();
                    try {
                        dateA = formatter.parse(arrA.get(0).toString());
                        dateB = formatter.parse(arrB.get(0).toString());
                    } catch (ParseException ex) {
                        Logger.getLogger(ValueComparator.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (dateA.before(dateB)) {
                        return 0;
                    } else if (dateA.after(dateB)) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            };
SortedMap sorted_map = new TreeMap(arrayListComparer);
sorted_map.putAll(map);

Solution

  • When you're using SortedMap or SortedSet your Comparator should return 0 only if two objects are equals. Because it treats key equality by this criteria.

    See natural ordering: http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

    For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.