Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To arrange an ArrayList in Java Android based on another ArrayList, you can use the Collections.sort() method to sort the first ArrayList based on the order of the second one.

Here's an example:

Assuming we have two ArrayLists: list1 and list2. list1 contains the elements that need to be sorted based on the order of list2.

ArrayList<String> list1 = new ArrayList<>();
list1.add("Apple");
list1.add("Banana");
list1.add("Orange");
list1.add("Pear");

ArrayList<String> list2 = new ArrayList<>();
list2.add("Banana");
list2.add("Orange");
list2.add("Apple");
list2.add("Pear");

In this example, we want to sort list1 in the same order as list2.

To sort list1, we can use the Collections.sort() method and provide it with a custom Comparator that compares the order of elements based on their index in list2.

Collections.sort(list1, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        int index1 = list2.indexOf(s1);
        int index2 = list2.indexOf(s2);
        return Integer.compare(index1, index2);
    }
});

The compare() method compares the elements in list1 based on their index in list2. If an element is not found in list2, it will be sorted at the end of list1.

After sorting list1, it will contain the following elements in the same order as list2: "Banana", "Orange", "Apple", "Pear".