Java List Move Item moveBackward(final List list, final int[] indices)

Here you can find the source of moveBackward(final List list, final int[] indices)

Description

Moves elements specified by their indices backward by 1.

License

Apache License

Parameter

Parameter Description
T type of the elements of the list
list list whose elements to move
indices indices of elements to be moved backward by 1

Return

true if moving was performed; false otherwise

Declaration

public static <T> boolean moveBackward(final List<T> list, final int[] indices) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Arrays;

import java.util.List;

public class Main {
    /**/*from w  ww  .j ava  2  s  . c  o  m*/
     * Moves elements specified by their indices backward by 1.
     * 
     * <p>
     * If the specified indices contains 0, then nothing is moved (the first element cannot be moved backward).
     * </p>
     * 
     * <p>
     * Implementation note: the received indices array might be rearranged. If this is unwanted, pass a copy of the original array.
     * </p>
     * 
     * @param <T> type of the elements of the list
     *          
     * @param list list whose elements to move
     * @param indices indices of elements to be moved backward by 1
     * @return true if moving was performed; false otherwise
     *       
     * @see #moveForward(List, int[])
     */
    public static <T> boolean moveBackward(final List<T> list, final int[] indices) {
        if (indices.length == 0)
            return false; // Nothing to move

        // Sort indices and iterate over them upward
        Arrays.sort(indices);
        if (indices[0] == 0)
            return false; // Cannot move backward as the first element is marked to be moved

        for (final int idx : indices) {
            final T element = list.get(idx);
            list.set(idx, list.get(idx - 1));
            list.set(idx - 1, element);
        }

        return true;
    }
}

Related

  1. getLongestLine(String text, List partsToRemove, String separator)
  2. getRemoveAll(List list1, Collection list2)
  3. minus(List initialList, List elementsToRemove)
  4. move(List aList, int anIndex1, int anIndex2)
  5. move(List collection, int indexToMoveFrom, int indexToMoveAt)
  6. moveBefore(List list, T element, T referenceElement)
  7. moved(List old, List nu, Collection added, Collection removed)
  8. moveDownItems(List list, int[] positions)
  9. moveElementInList(List list, int targetIndex, int sourceIndex)

    HOME | Copyright © www.java2s.com 2016