Java List Move Item moveRight(int offset, T element, List list)

Here you can find the source of moveRight(int offset, T element, List list)

Description

This method does the same as #moveLeft(int,Object,List) but it moves the specified element to the right instead of the left.

License

Open Source License

Declaration

public static <T> List<T> moveRight(int offset, T element, List<T> list) 

Method Source Code

//package com.java2s;
/*//from w  w w .  j a va2  s .  co m
 * Copyright (C) 2005-2014 Alfresco Software Limited.
 *
 * This file is part of Alfresco
 *
 * Alfresco is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Alfresco is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

import java.util.List;

import java.util.NoSuchElementException;

public class Main {
    /**
     * This method does the same as {@link #moveLeft(int, Object, List)} but it moves the specified element
     * to the right instead of the left.
     */
    public static <T> List<T> moveRight(int offset, T element, List<T> list) {
        final int elementIndex = list.indexOf(element);

        if (elementIndex == -1) {
            throw new NoSuchElementException("Element not found in provided list.");
        }

        if (offset == 0) {
            return list;
        } else {
            int newElementIndex = elementIndex + offset;

            // Ensure that the element will not move off the end of the list.
            if (newElementIndex >= list.size()) {
                newElementIndex = list.size() - 1;
            } else if (newElementIndex < 0) {
                newElementIndex = 0;
            }

            List<T> result = new ArrayList<>(list);
            result.remove(element);

            result.add(newElementIndex, element);

            return result;
        }
    }
}

Related

  1. moveItem(List list, Object oldItem, int newIndex)
  2. moveItemIdInSecond(final List list)
  3. moveItems(List list, int[] indices, int moveby, boolean up)
  4. moveLeft(int offset, T element, List list)
  5. moveOnePositionUp(final List list, final T object)
  6. moveRows(final List allRows, final List rowsToMove, final int index)
  7. moveToFront(List aList, Object anObj)
  8. moveTop(List list, int[] indices)
  9. moveUp(final List list, final T toMoveUp)