Sorting 2D array of strings in Java
You must use the Arrays.sort() method. This method takes a Comparator as argument. The sort method delegates to the comparator to determine if one element of the array must be considered bigger, smaller or equal to another element. Since every element of the outer array is an array, the comparator will have to compare arrays (of Strings).
The arrays must be compared based on the value of their second element. This second element is a String which in fact represents a double number. So you'll have to transorm the strings into numbers, else the order will be lexicographical (20 come before 3) rather than numerical.
The comparator could thus look like this :
public class StrinArrayComparator implements Comparator<String[]> {
@Override
public int compare(String[] array1, String[] array2) {
// get the second element of each array, andtransform it into a Double
Double d1 = Double.valueOf(array1.[1]);
Double d2 = Double.valueOf(array2.[1]);
// since you want a descending order, you need to negate the
// comparison of the double
return -d1.compareTo(d2);
// or : return d2.compareTo(d1);
}
}
Sort 2D String array in java
You can use the Comparator function, but you have to comprehend how a 2D array is represented in the memory.
String[][] multi = new String [][]{
{"Josef", "cool"},
{"Josef", "bat"},
{"zeta", "doen"}
};
This means that multi is an array of array. The first index of multi is an array with contents "Josef" and "cool". The second "Josef" and "bat". And so on.
More visually:
multi ----> [ ][ ][ ]
| | |
| | \->["zeta", "doen"]
| |
| \-> ["Josef"]["bat"]
|
\-> ["Josef"]["cool"]
When using the Array.sort()
, the comparator receives a 1D array as arguments. So when the arguments are String[] first, String[] second
then in memory, you have (when the Array.sort()
function is doing the first step)
first --> ["Josef"]["cool"]
second--> ["Josef"]["bat"]
So, in order to sort correctly, you have to check the first element. If it matches, then check the second element. Hence I've adapted your comparator class;
Arrays.sort(multi, new Comparator<String[]>(){
@Override
public int compare(String[] first, String[] second){
// compare the first element
int comparedTo = first[0].compareTo(second[0]);
// if the first element is same (result is 0), compare the second element
if (comparedTo == 0) return first[1].compareTo(second[1]);
else return comparedTo;
}
});
This should do the job.
Sorting 2D array of strings in alphabetical order
You can create a custom comparator implementing the interface Comparator
that takes the String[]
arrays (array 2D rows) as argument and comparing the first elements of the two arrays like below:
public class CustomComparator implements Comparator<String[]> {
@Override
public int compare(String[] row1, String[] row2) {
return row1[0].compareTo(row2[0]);
}
}
After you can execute the sorting in your main
method:
public static void main(String[] args) {
String[][] emp = {
{"Victor ", "ZSA"},
{"Fred ", "HAN"},
{"Drake ", "SOL"},
{"Albert ", "TUR"},
{"Eric ", "CAN"}};
Arrays.sort(emp, new CustomComparator());
System.out.println("String 1: String 2: ");
for (int i = 0; i < emp.length; i++) {
for (int j = 0; j < emp[0].length; j++) {
System.out.printf("%9s", emp[i][j]);
}
System.out.println();
}
}
Sorting 2D String Array with BUBBLESORT in java
public static String[][] stableSort(String[][] table, int column) {
int i=0,j=0;
String[] temp = null;
boolean swap=true;
while(swap)
for (i = 0; i < table.length - 1; i++) {
swap=false;
if(table[i][column].compareTo(table[i+1][column]) > 0){
temp = table[i];
table[i] = table[i+1];
table[i+1]=temp;
swap=true;
}
}
return table;
}
It keeps applying the bubblesort until no more swaps are performed. At that point,the condition while(swap) is no longer satisfied and the method returns.
Tried in a main and it works (if I understand what you meant):
public static void main(String[] args) {
String[][] table = {
{"z", "b", "v"},
{"s", "w", "a"},
{"r", "c", "h"}
};
table = stableSort(table,1);
for(int i = 0; i < table.length; i++){
for(int j = 0; j < table[0].length; j++){
System.out.printf("%5s ", table[i][j]);
}
System.out.println();
}
}
this outputs:
z b v
r c h
s w a
Sort 2D String Array with respect to a column in Java
Use stream
and Comparator
Then you could sort that array how ever you want :
String[][] array1 = {{"54", "jim", "delhi"},
{"67", "dwight", "bangalore"},
{"39", "pam", "pune"}};
List<String[]> collect1 = Arrays.stream(array1).sorted(Comparator.comparing(a -> a[1])).collect(Collectors.toList());
String[][] sortedArray = new String[array1.length][3];
for (int i = 0; i < collect1.size(); i++) {
sortedArray[i] = collect1.get(i);
}
System.out.println(Arrays.deepToString(sortedArray));
Sorting 2d String array using java
You are getting wrong answer because you were comparing 0th index of each row of 2D array which are String. So, according to string comparison logic the outputs are correct. To get the sorting order as integer, you have to convert 0th index of each row to Integer in your comparator.
Modify your sort method call like below which should work according to your expectation because a[0]
and b[0]
are converted to Integer before comparison:
Arrays.sort(customerArray, (a, b)->Integer.valueOf(a[0]).compareTo(Integer.valueOf(b[0])));
Output:
10
Akhil
Pune
20
Rajni
Hyderabad
30
Praveen
Delhi
100
Rohith
Chennai
101
Sam
Bangalore
How to sort multidimensional string array by one column in integer value in java?
Using Java 8 streams:
String[][] out = Arrays.stream(names)
.sorted(Comparator.comparing(x -> -Integer.parseInt(x[1])))
.toArray(String[][]::new);
How would I sort a 2D array in Java?
If you only want to sort the rows, I think it can be done like this:
Arrays.sort(a, (o1, o2) -> {
String firstO1Element = o1[0];
String firstO2Element = o2[0];
return firstO1Element.compareTo(firstO2Element);
});
This gives the following output:
Bob Smith Q 420
John Doe B 999
Name Here T 123
Sort Multidimensional String Array Without Using Array.sort
You can do like this,:
for(int i=0;i<numContacts;i++) {
for(int j=i+1;j<numContacts;j++) {
if(contactsArray [i][1].compareTo(contactsArray [j][1])>0) {
String[] temp = contactsArray [i];
contactsArray [i] = contactsArray [j];
contactsArray [j] = temp;
}
}
}
Sort a two dimensional String array with Arrays.sort based on a chosen column
Sure, just pass the column index in as a parameter of the comparator.
class ColumnComparator<T extends Comparable<T>> implements Comparator<T[]> {
private final int column;
ColumnComparator(int column) { this.column = column; }
@Override public int compare(T[] a, T[] b) {
return a[column].compareTo(b[column]);
}
}
or, more simply, if it is always column 1 and string arrays:
class ColumnComparator implements Comparator<String[]> {
@Override public int compare(T[] a, T[] b) {
return a[1].compareTo(b[1]);
}
}
Related Topics
Advantage of Set and Get Methods VS Public Variable
CSV File with "Id" as First Item Is Corrupt in Excel
Absolute Minimum Code to Get a Valid Oauth_Signature Populated in Java or Groovy
Check Is a Point (X,Y) Is Between Two Points Drawn on a Straight Line
Spring 3 MVC: One-To-Many Within a Dynamic Form (Add/Remove on Create/Update)
How Does the JPA @Sequencegenerator Annotation Work
Efficient Intersection of Two List<String> in Java
Ways to Save Enums in Database
Initializing an Array in Java Using the 'Advanced' for Each Loop
How to Retrieve the Autoincrement Id from a Prepared Statement
How to Set Same Scale for Domain and Range Axes Jfreechart
How to Prevent Parameter Binding from Interpreting Commas in Spring 3.0.5
Java - Read File and Split into Multiple Files
Comparing Date Strings in Java
How to Convert a Date to Milliseconds
Is It Necessary to Close Each Nested Outputstream and Writer Separately