Issue
I have String array which has 3 columns (id, name, city), I want to sort the array in ascending order with respect to name column. Please help me with this.
String[][] array1 = {{"54","jim","delhi"},
{"67","dwight","bangalore"},
{"39","pam","pune"}};
Expected output should be:
array1 = {{"67","dwight","bangalore"},
{"54","jim","delhi"},
{"39","pam","pune"}};
Solution
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));
Answered By – Lrrr
Answer Checked By – David Goodson (BugsFixing Volunteer)