开发者

collections for sorting employee details by id & firstname

I have written a code t开发者_如何学编程o sort name by id and firstname.

import java.io.*;
import java.util.*;
public class TestEmployeeSort  {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String option=null;
        System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
        List<Employee> coll = Name_Insert.getEmployees();

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        option=br.readLine();

        int a=Integer.parseInt(option);

             switch(a)
             {
             case 1:
             Collections.sort(coll);
             printList(coll);
             break;
             case 2:
             Collections.sort(coll,new EmpSortByFirstName());// sort method   
             printList(coll);
             break;
             case 3:
             Collections.sort(coll,new SortByLastName());// sort method   
             printList(coll);
             }
             } 
    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");

        for (int i=0;i<list.size();i++) {  
            Employee e=list.get(i);
            System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() +"\t" + e.getDate_Of_Joining()+"\t"+e.getDate_Of_Birth());
            }
        }

    }

for sorting by id and first name i have this code in the Sort_this class

public class EmpSortByFirstName implements Comparator<Employee>{ 
        public int compare(Employee o1, Employee o2) {  
            return o1.getFirstName().compareTo(o2.getFirstName());    }}

similarly for id. Now i want to change my program like i have to get input from uset on which basis you want to sort. If the user gives id, I have to sort by id. If the user gives firstname then sort by first name. I want to use if statement. If user enters 1 it has to sort by id 2 it has to sort by first name


Create a map of user input tokens (string, integer, etc.) to Comparator<Employee>, and just use the appropriate one.


Did you mean you want to get rid of using switch? If so, you can try having a map of registered soter:

import java.io.*;
import java.util.*;

public class TestEmployeeSort {

    private static class EmployeeSortingManager {

        private final List list;
        private final Map<Integer, Comparator> registeredSorter = new HashMap<Integer, Comparator>();

        public EmployeeSortingManager(List list) {
            this.list = list;
            registerAvailableSorters();
        }

        private void registerAvailableSorters() {
            registeredSorter.put(1, null);
            registeredSorter.put(2, new EmpSortByFirstName());
            registeredSorter.put(3, new SortByLastName());
        }

        public void sortBy(int i) {
            Comparator comparator = registeredSorter.get(i);
            if (registeredSorter.get(i) != null) {
                Collections.sort(list, comparator);
            } else {
                Collections.sort(list);
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String option = null;
        System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
        List<Employee> coll = Name_Insert.getEmployees();
        EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        option = br.readLine();

        int a = Integer.parseInt(option);

        employeeSortingManager.sortBy(a);

        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");

        for (int i = 0; i < list.size(); i++) {
            Employee e = list.get(i);
            System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
        }
    }
}

Another attemp to remove implementation of Every single comparator through the use of reflection. This is mmore complicated and may introduced more error if you are working with values which are not Comparable, e.g. String, Integer, Double. You will have to be careful.

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class TestEmployeeSort {

    private static class EmployeeSortingManager {

        private final List list;
        private final Map<Integer, Method> registeredSorter = new HashMap();
        private BasicComparator comparator = new BasicComparator();

        public EmployeeSortingManager(List list) {
            this.list = list;
            registerAvailableSorters();
        }

        private void registerAvailableSorters() {
            registeredSorter.put(1, null);
            registeredSorter.put(2, getEmployeeGetMethod("firstName"));
            registeredSorter.put(3, getEmployeeGetMethod("lastName"));
        }

        private Method getEmployeeGetMethod(String fieldName) {
            Method method = null;
            try {
                // create java style get method name from field name, e.g. getFieldName from fieldName
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                method = Employee.class.getMethod(getMethodName);
            } catch (NoSuchMethodException ex) {
            } catch (SecurityException ex) {
            }
            // null is return if you give invalid field name
            return method;
        }

        public void sortBy(int i) {
            Method get = registeredSorter.get(i);
            if (get != null) {
                comparator.setGetMethod(get);
                Collections.sort(list, comparator);
            } else {
                Collections.sort(list);
            }
        }
    }

    private static class BasicComparator implements Comparator<Employee> {

        private Method aGetMethod = null;

        public void setGetMethod(Method aGetMethod) {
            this.aGetMethod = aGetMethod;
        }

        @Override
        public int compare(Employee o1, Employee o2) {
            try {
                Object value1 = aGetMethod.invoke(o1);
                Object value2 = aGetMethod.invoke(o2);
                if (value1 instanceof Comparable && value2 instanceof Comparable) {
                    // this should work with String, Integer, Double, etc. They all implement Comparable interface.
                    return ((Comparable) value1).compareTo((Comparable) value2);
                } else {
                    // you will need to add your own comparision for other type of variable;
                    // obviously it is not possible to have a single comparison
                    // if your get method return something else.
                }
            } catch (IllegalAccessException ex) {
            } catch (IllegalArgumentException ex) {
            } catch (InvocationTargetException ex) {
            }
            // if cannot compare then they are equal.
            return 0;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String option = null;
        System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
        List<Employee> coll = Name_Insert.getEmployees();
        EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        option = br.readLine();

        int a = Integer.parseInt(option);

        employeeSortingManager.sortBy(a);

        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");

        for (int i = 0; i < list.size(); i++) {
            Employee e = list.get(i);
            System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜