Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a two dimensional array based on one column

In Java, I have a data in my array like the following

2009.07.25 20:24 Message A 2009.07.25 20:17 Message G 2009.07.25 20:25 Message B 2009.07.25 20:30 Message D 2009.07.25 20:01 Message F 2009.07.25 21:08 Message E 2009.07.25 19:54 Message R 

I would like to sort it based on the first column, so my final data can look like this

2009.07.25 19:54 Message R 2009.07.25 20:01 Message F 2009.07.25 20:17 Message G 2009.07.25 20:24 Message A 2009.07.25 20:25 Message B 2009.07.25 20:30 Message D 2009.07.25 21:08 Message E 

The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.

like image 869
Lenin Raj Rajasekaran Avatar asked Feb 05 '11 15:02

Lenin Raj Rajasekaran


People also ask

How do you sort a two dimensional array by column value?

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method. const arr = [ [12, "AAA"], [12, "BBB"], [12, "CCC"], [28, "DDD"], [18, "CCC"], [12, "DDD"], [18, "CCC"], [28, "DDD"], [28, "DDD"], [58, "BBB"], [68, "BBB"], [78, "BBB"], ]; const sortedArr = arr.

How do you sort a 2D array?

Example #2 Example for 2D array sorting in Java to sort all elements of a 2D array by column-wise. As in the above rewrite program, the sort() method is used to iterate each element of a 2D array and sort the array column-wise. Finally, the print method displays all the elements of the 2D array.

How do I sort an array by a column?

NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.

How do I sort a 2D array column wise in Python?

Sorting 2D Numpy Array by column at index 1 Select the column at index 1 from 2D numpy array i.e. It returns the values at 2nd column i.e. column at index position 1 i.e. Now get the array of indices that sort this column i.e. It returns the index positions that can sort the above column i.e.


2 Answers

Sort a two dimensional array based on one column
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.

Since you say 2-D array, I assume "date of format ..." means a String. Here's code for sorting a 2-D array of String[][]:

import java.util.Arrays; import java.util.Comparator;  public class Asdf {      public static void main(final String[] args) {         final String[][] data = new String[][] {                 new String[] { "2009.07.25 20:24", "Message A" },                 new String[] { "2009.07.25 20:17", "Message G" },                 new String[] { "2009.07.25 20:25", "Message B" },                 new String[] { "2009.07.25 20:30", "Message D" },                 new String[] { "2009.07.25 20:01", "Message F" },                 new String[] { "2009.07.25 21:08", "Message E" },                 new String[] { "2009.07.25 19:54", "Message R" } };          Arrays.sort(data, new Comparator<String[]>() {             @Override             public int compare(final String[] entry1, final String[] entry2) {                 final String time1 = entry1[0];                 final String time2 = entry2[0];                 return time1.compareTo(time2);             }         });          for (final String[] s : data) {             System.out.println(s[0] + " " + s[1]);         }     }  } 

Output:

2009.07.25 19:54 Message R 2009.07.25 20:01 Message F 2009.07.25 20:17 Message G 2009.07.25 20:24 Message A 2009.07.25 20:25 Message B 2009.07.25 20:30 Message D 2009.07.25 21:08 Message E 
like image 153
Bert F Avatar answered Sep 28 '22 00:09

Bert F


class ArrayComparator implements Comparator<Comparable[]> {     private final int columnToSort;     private final boolean ascending;      public ArrayComparator(int columnToSort, boolean ascending) {         this.columnToSort = columnToSort;         this.ascending = ascending;     }      public int compare(Comparable[] c1, Comparable[] c2) {         int cmp = c1[columnToSort].compareTo(c2[columnToSort]);         return ascending ? cmp : -cmp;     } } 

This way you can handle any type of data in those arrays (as long as they're Comparable) and you can sort any column in ascending or descending order.

String[][] data = getData(); Arrays.sort(data, new ArrayComparator(0, true)); 

PS: make sure you check for ArrayIndexOutOfBounds and others.

EDIT: The above solution would only be helpful if you are able to actually store a java.util.Date in the first column or if your date format allows you to use plain String comparison for those values. Otherwise, you need to convert that String to a Date, and you can achieve that using a callback interface (as a general solution). Here's an enhanced version:

class ArrayComparator implements Comparator<Object[]> {     private static Converter DEFAULT_CONVERTER = new Converter() {         @Override         public Comparable convert(Object o) {             // simply assume the object is Comparable             return (Comparable) o;         }     };     private final int columnToSort;     private final boolean ascending;     private final Converter converter;       public ArrayComparator(int columnToSort, boolean ascending) {         this(columnToSort, ascending, DEFAULT_CONVERTER);     }      public ArrayComparator(int columnToSort, boolean ascending, Converter converter) {         this.columnToSort = columnToSort;         this.ascending = ascending;         this.converter = converter;     }      public int compare(Object[] o1, Object[] o2) {         Comparable c1 = converter.convert(o1[columnToSort]);         Comparable c2 = converter.convert(o2[columnToSort]);         int cmp = c1.compareTo(c2);         return ascending ? cmp : -cmp;     }  }  interface Converter {     Comparable convert(Object o); }  class DateConverter implements Converter {     private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm");      @Override     public Comparable convert(Object o) {         try {             return df.parse(o.toString());         } catch (ParseException e) {             throw new IllegalArgumentException(e);         }     } } 

And at this point, you can sort on your first column with:

Arrays.sort(data, new ArrayComparator(0, true, new DateConverter()); 

I skipped the checks for nulls and other error handling issues.

I agree this is starting to look like a framework already. :)

Last (hopefully) edit: I only now realize that your date format allows you to use plain String comparison. If that is the case, you don't need the "enhanced version".

like image 25
Costi Ciudatu Avatar answered Sep 28 '22 02:09

Costi Ciudatu