简体   繁体   中英

How to sort Arraylist<String > based on another arraylist<String> in Kotlin

In my application I have 2 arraylists. One coming from server and another from assets. I want to sort server arraylist based on order of asset arraylist in Kotlin. eg val serverArraylist= { “xyz”, “abc”, “pqr”} val assetsList = { “abc”, “pqr”, “xyz”}

Expected output should be, serverArraylist = { “abc”, “pqr”, “xyz”}

Both the list may not always contain same number of elements. Sometimes serverlist may contain fewer elements But will not contain elements other than local list. Like, serverList= {xyz, pqr} Then expected list should be, severList= {pqr, xyz}

Any help or idea highly appreciated. Thanks in advance.

I have had similar problems in the past where the ordering of list A is based on the ordering of list B. I dont think it will work if the lists are different sizes. Otherwise, you need to have control of the 'swap' method in the sort, so that when list B elements are swapped, then so are the elements in list A. I dont know of a way to override this in Kotlin sort methods so in the past I wrote my own bubble sort method and swapped in both places. Other posters have given this which might help: java sorting with comparator and swap function

When serverArraylist only contains elements also contained in assetsList , you don't need to sort any list. The only thing you'd have to do is filter assetsList to only contain the elements of serverArraylist .

assetsList.filter { it in serverArraylist }
 val a = listOf("xyz","abc" ,"pqr" )
 val b = listOf("abc" ,"pqr", "xyz")
 val c = a + b
 val d = c.distinct().sorted()

This will give you

[abc, pqr, xyz]

You could clear the serverArrayList and then addAll the elements from the assetsList to the serverArrayList.

If you are unfamiliar with ArrayList operations you can find more HERE .

Edit: My apologies. I did not understand your question originally. You could use a hashmap to help you keep track of the desired indexes and elements of serverArrayList. The process should be something like this:

  1. Iterate over serverArrayList
  2. For each element in serverArrayList get it's corresponding index from assetsList with indexOf().
  3. Put each pair (index, element) into a hash map.
  4. Use the hash map to populate the new serverArrayList.

Look out for Out of Bounds errors as the index obtained could be larger than the size of serverArrayList, since you mentioned it could be smaller in size compared to assetsList.

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