java Arrays.sort 2d array

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

SO,

I am looknig to sort the following array based on the values of [][0]

double[][] myArr = new double[mySize][2]; 

so for ex, myArr contents is:

1      5 13     1.55 12     100.6 12.1   .85 

I want it to get to :

1      5 12     100.6 12.1   .85 13     1.55 

I am looking to do this without have to implement my own sort. Any help is appreciated, thanks.

回答1:

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= { {1, 5}, {13, 1.55}, {12, 100.6}, {12.1, .85} };  java.util.Arrays.sort(array, new java.util.Comparator() {     public int compare(double[] a, double[] b) {         return Double.compare(a[0], b[0]);     } }); 


回答2:

Welcome Java 8:

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0])); 


回答3:

You need to implement a Comparator like so:

public static void main(String[] args) throws IOException {     final Double[][] doubles = new Double[][]{{5.0, 4.0}, {1.0, 1.0}, {4.0, 6.0}};     final Comparator arrayComparator = new Comparator() {         @Override         public int compare(Double[] o1, Double[] o2) {             return o1[0].compareTo(o2[0]);         }     };     Arrays.sort(doubles, arrayComparator);     for (final Double[] arr : doubles) {         System.out.println(Arrays.toString(arr));     } } 

Output:

[1.0, 1.0] [4.0, 6.0] [5.0, 4.0] 


回答4:

Although this is an old thread, here are two examples for solving the problem in Java8.

sorting by the first column ([][0]):

double[][] myArr = new double[mySize][2]; // ... java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0])); 

sorting by the first two columns ([][0], [][1]):

double[][] myArr = new double[mySize][2]; // ... java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0]).thenComparingDouble(a -> a[1])); 


回答5:

import java.util.*;  public class Arrays2 {     public static void main(String[] args)     {         int small, row = 0, col = 0, z;         int[][] array = new int[5][5];          Random rand = new Random();         for(int i = 0; i 

Good Luck



回答6:

For a general solution you can use the Column Comparator. The code to use the class would be:

Arrays.sort(myArr, new ColumnComparator(0)); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!