Java List Swap swap(List list, int minIndex, int maxIndex)

Here you can find the source of swap(List list, int minIndex, int maxIndex)

Description

Method to swap elements at two indexes

License

Open Source License

Parameter

Parameter Description
list a parameter
minIndex a parameter
maxIndex a parameter

Return

List

Declaration

public static <T> List<T> swap(List<T> list, int minIndex, int maxIndex) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**//from  w  w w . j  a v  a 2s.  c  om
     * Method to swap elements at two indexes
     * 
     * @param list
     * @param minIndex
     * @param maxIndex
     * @return {@link List<T>}
     */
    public static <T> List<T> swap(List<T> list, int minIndex, int maxIndex) {
        if (list != null && list.size() > 2 && maxIndex > minIndex) {
            List<T> updatedList = new ArrayList<>();
            T elementAtMinIndex = list.get(minIndex);
            T elementAtMaxIndex = list.get(maxIndex);
            for (int i = 0; i < list.size(); i++) {
                if (i != minIndex && i != maxIndex) {
                    updatedList.add(i, list.get(i));
                } else if (i == minIndex) {
                    updatedList.add(i, elementAtMaxIndex);
                } else if (i == maxIndex) {
                    updatedList.add(i, elementAtMinIndex);
                }
            }
            return updatedList;
        }
        return null;
    }
}

Related

  1. swap(List list, Object object1, Object object2)
  2. swap(List a, int i, int j)
  3. swap(List items, int index1_, int index2_)
  4. swap(List list, int i1, int i2)
  5. swap(List list, int index1, int index2)
  6. swapElements(List list, T element1, T element2)
  7. swapItems(final List data, int from, int to)
  8. swapListElements(List list, int idx1, int idx2)