0

How to format the data based on Date

I am using TreeMap and want to sort based on Date

I have a List of Persons and i want to sort based on dateOfBirth

package com;

    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.TreeMap;

    public class GroupByDemoInJava8 {
        public static void main(String args[]) throws Exception {
            try {
                List<Person> personList = new ArrayList<>(); // Date Format is MM/DD/YYYY
                personList.add(new Person("Mike", "London", 21, "01/01/1981"));
                personList.add(new Person("John", "London", 21, "01/02/1981"));
                personList.add(new Person("Prasanna", "London", 23, "04/28/1990"));
                personList.add(new Person("Monobo", "Tokyo", 23, "04/28/1990"));
                personList.add(new Person("Sam", "Paris", 23, "07/12/1992"));
                personList.add(new Person("Nadal", "Paris", 31, "04/02/1992"));

                String patternInput = "MM/dd/yyyy";

                SimpleDateFormat simpleDateFormatInput = new SimpleDateFormat(patternInput);

                String outputPattern = "MMM-yy";
                SimpleDateFormat simpleDateFormatOutput = new SimpleDateFormat(outputPattern);

                Map<String, List<Person>> personByMap = new TreeMap<String, List<Person>>();

                for (Person p : personList) {
                    Date inputDate = simpleDateFormatInput.parse(p.getDateOfBirth());

                    String outPutDate = simpleDateFormatOutput.format(inputDate);

                    if (!personByMap.containsKey(outPutDate)) {
                        personByMap.put(outPutDate, new ArrayList<>());
                    }

                    personByMap.get(outPutDate).add(p);

                }

                System.out.println(personByMap);


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    class Person {
        private String name;
        private String city;
        private int age;
        private String dateOfBirth;

        public String getDateOfBirth() {
            return dateOfBirth;
        }

        public void setDateOfBirth(String dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
        }

        public Person(String name, String city, int age, String dateOfBirth) {
            this.name = name;
            this.city = city;
            this.age = age;
            this.dateOfBirth = dateOfBirth;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person [name=" + name + ", city=" + city + ", age=" + age + "]";
        }
    }
user974802
  • 3,397
  • 10
  • 26
  • 29

2 Answers2

1

The new java time classes are a huge improvement. For a birthday a MonthDay is ideal. It is a Comparable<MonthDay> so you can use it for sorting.

Sorting can be done by creating a Comparator. Here I compose the comparator by first a person to birth day mapping method, and then by a Person getter of its name.

Map<String, List<Person>> personByMap = new TreeMap<>(
        Comparator.comparing(this::birthDay)
                  .thenComparing(Person::getName));

MonthDay birthDay(String date) {
    LocalDate d = LocaleDate.parse(date, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
    return MonthDay.from(d);
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

All you need is custom comparator for the person that compares only the date of birth.

Collections.sort(personList, new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            //access your formatter simpleDateFormatInput here.
            return simpleDateFormatInput.format(o1.dateOfBirth).compareTo(simpleDateFormatInput.format(o2.dateOfBirth));
        }
    });
Ran
  • 333
  • 1
  • 4
  • 16
  • Wherever you want to sort the persons by date of birth. The `personList` will have the persons in the sorted order. – Ran Jul 26 '19 at 11:29
  • Will this code have any impact after i put it after personByMap.get(outPutDate).add(p); – user974802 Jul 26 '19 at 11:31
  • No impact on the map. But the ordering of persons in the list will be altered. Ofcourse! – Ran Jul 26 '19 at 11:40