简体   繁体   English

按ID和名字对员工详细信息进行排序的集合

[英]collections for sorting employee details by id & firstname

I have written a code to sort name by id and firstname. 我已经编写了一个代码,以按ID和名字对名称进行排序。

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 用于按ID和名字排序我在Sort_this类中有此代码

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

similarly for id. 同样适用于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. 如果用户提供ID,则必须按ID排序。 If the user gives firstname then sort by first name. 如果用户提供名字,则按名字排序。 I want to use if statement. 我想使用if语句。 If user enters 1 it has to sort by id 2 it has to sort by first name 如果用户输入1,则必须按ID 2进行排序,必须按名字进行排序

创建一个用户输入令牌(字符串,整数等)到Comparator<Employee>的映射,然后使用适当的映射。

Did you mean you want to get rid of using switch ? 您是不是想摆脱使用switch If so, you can try having a map of registered soter: 如果是这样,您可以尝试拥有已注册的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 , eg String , Integer , Double . 如果您使用的不是Comparable值,例如StringIntegerDouble ,这将更加复杂,并且可能会引入更多错误。 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());
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM