SortByHouseNo.java Source code

Java tutorial

Introduction

Here is the source code for SortByHouseNo.java

Source

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class SortByHouseNo implements Comparator<HouseNo> {

    @Override
    public int compare(HouseNo o1, HouseNo o2) {
        Integer first = Integer.valueOf(o1.getHouseno());
        Integer second = Integer.valueOf(o2.getHouseno());

        Integer f1 = Integer.valueOf(o1.getBlockno());
        Integer f2 = Integer.valueOf(o2.getBlockno());

        if (first.compareTo(second) == 0) {
            return f1.compareTo(f2);
        }
        return first.compareTo(second);
    }
}

public class Main {

    public static void main(String[] args) {
        String houseList[] = { "9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03", "9-3" };
        HouseNo house = null;
        ArrayList<HouseNo> sortedList = new ArrayList<>();
        for (String string : houseList) {
            String h = string.substring(0, string.indexOf('-'));
            String b = string.substring(string.indexOf('-') + 1);
            house = new HouseNo(h, b);
            sortedList.add(house);
        }

        System.out.println("Before Sorting :: ");
        for (HouseNo houseNo : sortedList) {
            System.out.println(houseNo);
        }

        Collections.sort(sortedList, new SortByHouseNo());
        System.out.println("\n\nAfter Sorting HouseNo :: ");
        for (HouseNo houseNo : sortedList) {
            System.out.println(houseNo);
        }
    }
}

class HouseNo {
    public HouseNo(String house, String block) {
        this.houseno = house;
        this.blockno = block;
    }

    String houseno;
    String blockno;

    public String getHouseno() {
        return houseno;
    }

    public void setHouseno(String houseno) {
        this.houseno = houseno;
    }

    public String getBlockno() {
        return blockno;
    }

    public void setBlockno(String blockno) {
        this.blockno = blockno;
    }

    @Override
    public String toString() {
        return "House -> " + this.getHouseno() + "-" + this.getBlockno();
    }
}