Pages

Saturday, October 29, 2016

Object Sorting to sort by string or integer by implementing comparable, comparator.

Write a program that use object sorting to sort by string or integer by  implementing comparable, comparator.

Program/Code:

Employee Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Comparator;

public class employee implements Comparable<employee>, Comparator<employee> {

    // instance variable
    private String name;
    private int Id;

    // constructor
    employee() {
    }

    public employee(String name, int Id) {
        this.name = name;
        this.Id = Id;
    }

    // getter & setter method
    public String getName() {
        return name;
    }

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

    public int getId() {
        return Id;
    }

    public void setId(int Id) {
        this.Id = Id;
    }

    // compare method 
    @Override
    public int compareTo(employee o) {
        int i;
        i = this.getName().compareTo(o.getName());
        return i;
    }

    @Override
    public int compare(employee o1, employee o2) {
        return o1.Id - o2.Id;
    }
}

EmployeeTest Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String args[]) {
        
        ArrayList<employee> arr = new ArrayList<>();
        arr.add(new employee("Ahmed", 5));
        arr.add(new employee("Akram", 3));
        arr.add(new employee("Shahid", 6));
        arr.add(new employee("Jamshad", 7));
        arr.add(new employee("Sabir", 9));

        Collections.sort(arr);
        System.out.println("Compare by String\n id ---- Name");
        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i).getId() + "    " + arr.get(i).getName());
        }

        Collections.sort(arr, new employee());
        System.out.println("\n\nCompare by int\n id ---- Name");
        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i).getId() + "    " + arr.get(i).getName());
        }
    }
}

Result:
Compare by String
 id ---- Name
5    Ahmed
3    Akram
7    Jamshad
9    Sabir
6    Shahid


Compare by int
 id ---- Name
3    Akram
5    Ahmed
6    Shahid
7    Jamshad
9    Sabir

No comments:

Post a Comment