简体   繁体   中英

Sort ArrayList A based on ArrayList B

Say for example I have:

ArrayList A; with values: "a","b", "c", "d", "e"

ArrayList B ; with values: "3","1", "5", "2", "4"

Then I performed

Collections.sort(B);

so then ArrayList B becomes:

"1","2", "3", "4", "5"

Now I want to sort ArrayList A based on the sort in ArrayList B , I should get ArrayListA :

"b","d", "a", "e", "c"

How can I achieve that? Sorry I'm still new to Android. Any help would be appreciated.

Just put the data into the TreeMap (which is a map sorted by natural ordering of its keys) and you're done.

Manual approach (if you want some programming practice) would be:

  • put both lists in a single map where keys come from list B and values from list A
  • get the keys from map and sort them
  • iterate over sorted keys and get values from the map and put them into new list.

As you can see this question has nothing to do with Android, it's just a simple programming task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM