简体   繁体   中英

Sort arrayList in ascending and descending order

The following method receives two array list of integers objects and a Boolean indicating the sorting order (ascending, if true; descending, if false), and returns an array list with all the elements from both arrays sorted. I know how to sort individual array list using Arrays.sort(array), but I am getting lost on how to combine the two array list.

public static ArrayList<Integer> getSorted(ArrayList<Integer> FIRST,
           ArrayList<Integer> SECOND, boolean ascendingly){

A hint to solve your problem .

  1. you can combine two arraylist into one either by adding them to a temp one, or adding two in either one.
  2. now call Arrays.sort method to sort the list.

for an array you can always use Arrays.sort()

And,if you want collections to be sorted you can use

Collections.sort(listName);

for ascending order,and

Collections.sort(listName, Collections.reverseOrder());

for descending order

Just a hint

Hope this helps! Good Luck!

Collections may be good for this case.
such as :

ArrayList<Integer> newList=new ArrayList<Integer>()
if(first not null && first.size() > 0){
   newList.addAll(first)
}
//so does second list
...
newList.AddAll(second)

if(newList.size>1){
  if(order){
    Collections.sort(newList)
  }else{
    Collections.reverse(newList)
  }
}
return newList

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