AndroidGuy007 AndroidGuy007 - 8 months ago 38
Android Question

Sort string array based on previous sorted array android java

hello i have 2 string array

private String names[] = {

private String desc[] = {
"this is drinks package",
"package for bikes",
"package cars"

// now i used


Now that the names are in correct A - Z order, how can I sort "desc" array based on "names" array?

for example after sorting array "names" result:


now i want the desc array to format same way so proper "desc" lie on proper "names"

result should be this

names = "Bikes,Cars,Drinks"
desc = "package for bikes","package cars,this is drinks package"

can we do this ?

The marked is duplicated this is not duplicate of descending anyway


Why not use classes?

As in Object-Oriented Principles, when you have data related to a specific topic, you put them in a class together.


NameDescription class implementing Comparable interface

public class NameDescription implements Comparable<NameDescription> {
    private String name;
    private String description;

    public NameDescription(String name, String description) { = name;
        this.description = description;

    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getDescription() {
        return description;
    public void setDescription(String description) {
        this.description = description;

    public int compareTo(NameDescription o) {
        return name.compareTo(o.getName());

Comparable interface provides the compareTo method which makes you able to define the comparison formula to compare the current object with another one (they don't even need to be of the same type). Arrays.sort method uses the compareTo method to sort the elements, so this way you have your data together and any sorting method will give you consistent results based on your compareTo method.

Sorter class:

public class Sorter {

    public static void main(String[] args) {
        NameDescription namesDescriptions[] = {
                new NameDescription("Drinks", "this is drinks package"),
                new NameDescription("Bikes", "package for bikes"),
                new NameDescription("Cars", "package cars"),


        // ASCENDING
        for(NameDescription nd : namesDescriptions) {
        for(NameDescription nd : namesDescriptions) {


        // DESCENDING
        for(int i=namesDescriptions.length-1; i>=0; i--) {
        for(int i=namesDescriptions.length-1; i>=0; i--) {