【问题标题】:How to sort a ArrayList<int[]>? [closed]如何对 ArrayList<int[]> 进行排序? [关闭]
【发布时间】:2017-03-15 07:56:57
【问题描述】:

如何排序一个ArrayList&lt;int[]&gt; 列表中的每个元素基本上就是一个元组。例如,一些元素看起来像:

[5,10] [8,6] [9,5]

我想根据元组中的第二个数字对ArrayList&lt;int[]&gt; 进行排序。因此,排序时它看起来像:

[9,5] [8,6] [5,10]

【问题讨论】:

  • 你为什么要为此标记java和python?更重要的是,展示你的代码尝试。 StackOverflow不是代码编写服务。
  • 您希望它按哪个值排序?索引 0 还是索引 1?

标签: java arrays list arraylist


【解决方案1】:

如果您使用的是 Java 8:

list.sort(Comparator.comparingInt(i -> i[1]));

【讨论】:

    【解决方案2】:

    使用比较器

    import java.util.*;
    
    public class sorter{
    
     public static void main(String []args){
    
        List<int []> list= new ArrayList<int []>();
       //[5,10] [8,6] [9,5] 
        list.add(new int[]{5,10});
        list.add(new int[]{8,6});
        list.add(new int[]{9,5});
    
         for(int [] a:list){
        System.out.println(a[0]+"--"+a[1]);
    
    
        }
         System.out.println("********************");
        Collections.sort(list, new IntArrayComparator());
        for(int [] a:list){
        System.out.println(a[0]+"--"+a[1]);
    
    
        }
     }
    }
    
    
    class IntArrayComparator implements Comparator<int[]> {
    @Override
    public int compare(int[] ia1, int[] ia2) {
        int e1 = ia1[1];
        int e2 = ia2[1];;
    
        if (e1 > e2) {
            return 1;
        } else if (e2>e1) {
            return -1;
        } else {
            return 0;
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-05
      • 1970-01-01
      • 2018-03-25
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2016-08-28
      • 2011-09-20
      相关资源
      最近更新 更多