简体   繁体   中英

How do i switch pairs of strings in an arraylist?

How would i flip each pair of values in a list? For example, If i have an arraylist ["aa"", "bb"", "cc"", "DDD", "happy", "snow"]. and wanted to the list afterwards to store ["bb"", "a"", "DDD", "cc"", "snow", "happy"]

I tried using a for loop but didnt get anything when i called the method.

 public static void flip2(ArrayList<String> list){


 for(int i =0; i <list.size(); i++){

 Collections.swap(list. i, (i+1){
 System.out.println("The new list = " + list));
    }
  }
}

I appreciate the help!!!

Just increment your index by 2 each time and swap element at index i and i + 1 .

public static void main(String[] args) {
  List<String> list = Arrays.asList("aa", "bb", "cc", "DDD", "happy", "snow");

  for(int i =0; i<list.size(); i+=2){
       Collections.swap(list, i, (i+1));
  }
  System.out.println("The new list = " + list);
}

Output :

The new list = [bb, aa, DDD, cc, snow, happy]

Note that this assume that your list have even number of objects into it.

If you want to handle all possible cases (whatever is the size() of the list) you can check that at each iteration, if (i+1) is inferior than the size.

for(int i =0; i+1<list.size(); i+=2){
    Collections.swap(list, i, (i+1));
}

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