Java – How to sort multiple ArrayLists together in java

How to sort multiple ArrayLists together in java… here is a solution to the problem.

How to sort multiple ArrayLists together in java

I’m working on an app that saves restaurant information, each restaurant has 5 information “as listed in the code below” and I need to sort restaurants by rate. However, after I sort by rate, I need to synchronize all the array lists together so that their information matches correctly.

I

have 5 ArrayLists and I need to sort one of them, but I also want to change the indexes of the other 4 ArrayLists so that they can fit into each other. I tried the map list but it tells me that I can do it with just 2 parameters instead of 5.

Here is my array list :

//******* Arrays that holds information of restaurants taken from SERVER
static public ArrayList<String> name = new ArrayList<String>();
static public ArrayList<String> lng = new ArrayList<String>();
static public ArrayList<String> lat = new ArrayList<String>();
static public ArrayList<String> address = new ArrayList<String>();
static public ArrayList<String> rate = new ArrayList<String>();
static public ArrayList<String> comment = new ArrayList<String>();
private Map<String, String> sorted = new HashMap<>(); Doesn't work with 5 parameters

I need to sort the rate list and also need to change the index of other lists.

Solution

You can create an object that contains various string properties in Restaurant.
So that you can only have a list and call sort on it to sort everything at once.

You must implement Comparable in this Restaurant class to define how your restaurants should be ordered.

Edit:

Your Restaurant class will look like this:

public class Restaurant implements Comparable<Restaurant>{

private String name;
    private String lng;
    private String lat;
    private String address;
    private String rate;
    private String comment;

...
    constructor/getters/setters
    ...

@Override
    public int compareTo(Restaurant rest) {
        TODO: check if rate is null if this can happen in your code
        return rate.compareTo(rest.rate); comparing on rate attribute
    }

}

Then you can replace your code with it

static public ArrayList<Restaurant> restaurants = new ArrayList<Restaurant>();
Collections.sort(restaurants);

Related Problems and Solutions