简体   繁体   中英

Sorting multiple lists with another sorted list?

Yeah I know, the title doesn't really mean much. This is what I am trying to do:

Banana | 3

Pineapple | 2

Apple | 1

I get this output from printing different lists with [list].get(i) + "|" + [anotherList].get(i) [list].get(i) + "|" + [anotherList].get(i)

Now, I want to sort [list] by alphabetical order, while maintaining the other list linked to it

This should be the expected output:

Apple | 1

Banana | 3

Pineapple | 2

How can I do so? Obviously I am not having trouble in sorting the list itself, I have trouble maintaining everything together. Also I have way more lists than 2 (they are not shown here).

I would suggest using a HashMap for your list items. The keys will be the list items and the corresponding values will be entries from other lists. For example, you have 3 lists. These are list , anotherList and anotherList2 .

First you set the values properly which are associated with the list keys. Declare a HashMap first for this.

Map<String, ArrayList<String>> map = new HashMap<>();

Now populate the data in your map like this.

for(int i = 0; i < list.size(); i++) {
    ArrayList<String> otherItems = new ArrayList<>();
    otherItems.add(anotherList.get(i));
    otherItems.add(anotherList2.get(i));
    map.put(list.get(i), otherItems);
}

Now simply sort the list for getting the fruits sorted alphabetically and hence get the corresponding values associated with it from those two different lists by searching them in the HashMap .

list.get(i) + "|" + getValuesSeperatedWithABar(map.get(list.get(i)))

I hope you get the idea.

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