2017-03-05 54 views
0

我需要澄清一下如何根据存储在每列中的值对二维数组列表进行排序。按列排序2D ArrayList

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


public class ArrayListSorter { 
    public static void main(String[] args){ 
     ArrayList<ArrayList<Double>> myArrayList = new ArrayList<>(); 
     int numInstances = 10; 
     int numAttributes = 10; 
     for(int i = 0; i< numInstances; i++){ 
      myArrayList.add(new ArrayList<Double>()); 
      for(int j = 0; j < numAttributes; j++){ 
       Random r = new Random(); 
       double val = r.nextDouble(); 
       myArrayList.get(i).add(val); 
      } 
     } 

     Collections.sort(myArrayList, new Comparator<ArrayList<Double>>() {  
      @Override 
      public int compare(ArrayList<Double> o1, ArrayList<Double> o2) { 
       return o1.get(2).compareTo(o2.get(2)); 
      }    
     }); 
     for(int i = 0; i < numInstances; i++){ 
      System.out.println(myArrayList.get(i)); 
     } 
    } 
} 

我设置了一个孤立的问题,它建立了一个填充随机双打的2D ArrayList。然后我可以按第一列(或者我在代码中指定的任何列)进行排序。我正在努力研究如何迭代到下一列,以便根据下一列中的值进行重新排序。每次对ArrayList排序后,我需要能够执行一组操作。

+0

我目前拥有的代码设置成通过第三列对ArrayList进行排序,该第三列表示为:return o1.get(2).compareTo(o2.get(2)); – jcarm2234

回答

0

可以实现自定义的比较如下 -

public class CustomComparator implements Comparator<ArrayList<Double>> { 

    private final int index; 

    public CustomComparator(int index) { 
     this.index = index; 
    } 

    public int compare(ArrayList<Double> first, ArrayList<Double> second) { 
     return first.get(index).compareTo(second.get(index)); 
    } 
} 

,然后再使用它与您的代码基础上的指数为顺序排序 -

for (int j = 0; j < numAttributes; j++) { 
    System.out.println("Sorting based on column " + (j+1)); 
    myArrayList.sort(new CustomComparator(j)); 
    for (int i = 0; i < numInstances; i++) { 
     System.out.println(myArrayList.get(i)); 
    } 
}