2010-12-01 3 views
2

idとfirstnameで名前をソートするコードを記述しました。 IDと最初の名前によってソートする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()); 
      } 
     } 

    } 

iがSort_thisクラスでこのコードを有する

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

同様にIDに対応します。 今私は、あなたがソートしたいと思うベースで、usetからの入力を得なければならないように私のプログラムを変更したいと思います。ユーザーがidを指定すると、idでソートする必要があります。ユーザがファーストネームを与えた場合、ファーストネームでソートします。 if文を使いたい。ユーザーが1を入力すると、ID 2でソートする必要があります。名前でソートする必要があります。

+0

あなたが直面している問題は何ですか?あなたはすでにあなたが望むことをするためのコードを持っているようです。 – casablanca

+0

「あなたがファーストネームを与えた場合」とはどういう意味ですか?ユーザーは入力に 'firstname'を入力する必要がありますか? –

答えて

1

ユーザー入力トークン(文字列、整数など)のマップをComparator<Employee>に作成し、適切なものを使用します。

0

switchを削除したいのですか?もしそうなら、あなたは登録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()); 
     } 
    } 
} 

リフレクションを使用して、一つ一つのコンパレータの実装を削除する別のattemp。これは複雑なもので、Comparableではない値で作業しているとエラーが多く発生する可能性があります。 String,Integer,Double。あなたは注意する必要があります。

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

それはうまく動作しますが、私が必要なのは、1つのcompareTo()だけフィールドの種類を並べ替えるために使用する必要があります。 – Sumithra

+0

新しいコードを追加しました。基本的には、Comparatorメソッドを実装しなくてもいいので、一般的に多くの作業を行う可能性があります。私はString型のフィールドだけで動作するよう実装しています。 Employeeクラスに他のタイプのフィールドが含まれている場合は、それを自分でBasicComparatorに追加する必要があります。 – gigadot

+0

また、速度が問題になる場合は、反射を使用することはお勧めしません。何百万人もの従業員がいないことを考えると、問題はありません。 – gigadot

関連する問題