Move an object in List up - Java java.util

Java examples for java.util:List Element

Description

Move an object in List up

Demo Code


//package com.book2s;
import java.util.ArrayList;

import java.util.List;

import java.util.function.Function;

public class Main {
    /**//from   w w w  .  ja v  a2  s  . co m
     * Move an object in List up
     * 
     * @param list
     * @param key
     * @param keyMapper
     * @return
     */
    public static <T, K> boolean moveUp(List<T> list, K key,
            Function<T, K> keyMapper, int n) {
        ArrayList<T> newList = new ArrayList<T>();
        boolean changed = false;
        for (int i = 0; i < list.size(); i++) {
            T item = list.get(i);

            if (i > 0 && key.equals(keyMapper.apply(item))) {
                int posi = i - n;
                if (posi < 0)
                    posi = 0;
                newList.add(posi, item);
                changed = true;
            } else
                newList.add(item);
        }

        if (changed) {
            list.clear();
            list.addAll(newList);
            return true;
        }
        return false;
    }

    public static <T, K> boolean moveUp(List<T> list, K key,
            Function<T, K> keyMapper) {
        return moveUp(list, key, keyMapper, 1);
    }
}

Related Tutorials