2016-10-14 66 views
-1

我有一個Object數組的列表。排序列表<Object[]>

List<Object[]> lFiles = new ArrayList<Object[]>(); 

我想對這個列表進行排序,我不確定實現它的最佳方式是什麼。我試過Comparator,但我沒有得到如何做到這一點。我正在使用這種技術,所以我可以將Iterator作爲testNG中的dataProvider使用。

任何人都可以告訴是否有任何其他好的方式返回列表作爲testNG中的數據提供者使用。

Complete方法

@DataProvider(name = "gFile") 
    //generated 
    public static Iterator<Object[]> getGenerated() 
    { 
     List<Object[]> lFiles = new ArrayList<Object[]>(); 
     listf(path + "generated/", 
       lFiles); 
     Collections.sort(lFiles, 
          new Comparator<Object>() 
          { 

           public int compare(Object o1, 
             Object o2) 
           { 
            return compare(o1.toString(), 
                o2.toString()); 
           } 
          }); 
     return lFiles.iterator(); 
    } 

public static void listf(String directoryName, 
      List<Object[]> lFiles) 
    { 
     File directory = new File(directoryName); 

     // get all the files from a directory 
     File[] fList = directory.listFiles(); 

     for(File file : fList) 
     { 
      if(file.isFile()) 
      { 
       if(file.getName().endsWith(".java")) 
        lFiles.add(new Object[] { file.getName() }); 
      } 
      else if(file.isDirectory()) 
      { 
       listf(file.getAbsolutePath(), 
         lFiles); 
      } 
     } 
    } 
+3

首先,你必須決定「排序」的含義。具體而言,您需要決定訂單的確定方式。爲什麼一個Object []應該在另一個Object []之前或之後出現? – VGR

+0

基本上它是文件列表(名稱),所以我想按字典順序對它們排序@VGR – RATHORE

+0

好吧,所以每個Object []只包含字符串。你只關心每個數組中的第一個字符串? – VGR

回答

2

如果你想使用Comparator你可以做類似下面的代碼進行排序。

static void test() { 
    List<Object[]> lFiles = new ArrayList<>(); 

    Collections.sort(lFiles , new Comparator<Object[]>() { 
     @Override 
     public int compare(Object[] o1, Object[] o2) { 
      // Write the logic how two array will compare. 
      return 0; 
     } 
    }); 
} 
+0

這是行不通的,我在使用新比較器時出現錯誤 {...} – RATHORE

+0

明白了,謝謝! – RATHORE