-8

I'm trying to sort objects in arrayList. May be like Node and Edge. For example: I have objects like this:

Object2[B, C], Object1[A, B], Object4[E, F], Object3[C, D], Object5[F, G],...

My question is how can I sort it into the groups like this:

Object1[A, B], Object2[B, C], Object3[C, D] = Group1 Object4[E, F], Object5[F, G] = Group2 ...

How can I do it?

Ramona
  • 159
  • 1
  • 10
  • 2
    There are literally dozens of sorting algorithms, and certainly implementations for each in multiple languages, and you couldn't find a single one to use or adapt for your use? This shows a distinct lack of ability or effort on your part, and doesn't follow what SO aims to be used for, i.e. answering specific coding questions. – AntonH Oct 13 '17 at 16:48
  • you can implement `Comparable`, then override the `compareTo` method according to your needs and then call the `Collections.sort(yourArrayList)` method. This is just one of the ways... – assembler Oct 13 '17 at 16:51
  • 1
    Possible duplicate of [Sort ArrayList of custom Objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – JT 1114 Oct 13 '17 at 16:53

1 Answers1

0

Use Comparable and Comparator as shown below, you can also visit https://www.journaldev.com/780/comparable-and-comparator-in-java-example for further details.

    import java.util.Comparator;

    class Employee implements Comparable<Employee> {

        private int id;
        private String name;
        private int age;
        private long salary;

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public long getSalary() {
            return salary;
        }

        public Employee(int id, String name, int age, int salary) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.salary = salary;
        }

        @Override
        public int compareTo(Employee emp) {
            //let's sort the employee based on id in ascending order
            //returns a negative integer, zero, or a positive integer as this employee id
            //is less than, equal to, or greater than the specified object.
            return (this.id - emp.id);
        }

        @Override
        //this is required to print the user friendly information about the Employee
        public String toString() {
            return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                    this.salary + "]";
        }
}

Default Sorting of Employees list: [[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]