Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Comparator;
import java.util.TreeSet;

public class Main {
    public static void main(String a[]) {
        // By using name comparator (String comparison)
        TreeSet<Empl> nameComp = new TreeSet<Empl>(new MyNameComp());
        nameComp.add(new Empl("R", 3));
        nameComp.add(new Empl("J", 6));
        nameComp.add(new Empl("C", 20));
        nameComp.add(new Empl("T", 2));

        System.out.println(nameComp);

        // By using salary comparator (int comparison)
        TreeSet<Empl> salComp = new TreeSet<Empl>(new MySalaryComp());
        salComp.add(new Empl("R", 3));
        salComp.add(new Empl("J", 6));
        salComp.add(new Empl("C", 20));
        salComp.add(new Empl("T", 2));
        System.out.println(salComp);

    }
}

class MyNameComp implements Comparator<Empl> {

    @Override
    public int compare(Empl e1, Empl e2) {
        return e1.getName().compareTo(e2.getName());
    }
}

class MySalaryComp implements Comparator<Empl> {

    @Override
    public int compare(Empl e1, Empl e2) {
        if (e1.getSalary() > e2.getSalary()) {
            return 1;
        } else {
            return -1;
        }
    }
}

class Empl {

    private String name;
    private int salary;

    public Empl(String n, int s) {
        this.name = n;
        this.salary = s;
    }

    public String getName() {
        return name;
    }

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

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public String toString() {
        return "Name: " + this.name + "-- Salary: " + this.salary;
    }
}