Ask Your Question
2

How to arrange an array list in Java Android based on another array list?

asked 2022-02-04 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-04-23 10:00:00 +0000

nofretete gravatar image

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".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-04 11:00:00 +0000

Seen: 7 times

Last updated: Apr 23 '22