Java List First Item addFirstAndRemoveOldIfNeed(List dest, List src)

Here you can find the source of addFirstAndRemoveOldIfNeed(List dest, List src)

Description

add First And Remove Old If Need

License

Open Source License

Parameter

Parameter Description
dest a parameter
src a parameter

Declaration

public static <T> void addFirstAndRemoveOldIfNeed(List<T> dest, List<T> src) 

Method Source Code


//package com.java2s;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class Main {

    public static <T> void addFirstAndRemoveOldIfNeed(List<T> dest, List<T> src) {
        if (dest == null) {
            return;
        }/*from w w w  .java2  s.co  m*/

        if (src == null || src.isEmpty()) {
            return;
        }

        removeDuplicate(dest, src);
        dest.addAll(0, src);
    }

    @SuppressWarnings("unchecked")
    public static <T> void removeDuplicate(List<T> dest, List<T> src) {
        if (dest == null) {
            return;
        }

        if (src == null || src.isEmpty()) {
            return;
        }

        int capacity = dest.size() > src.size() ? dest.size() : src.size();
        HashMap<T, Integer> map = new HashMap<T, Integer>(capacity);
        for (int i = 0; i < dest.size(); i++) {
            map.put(dest.get(i), i);
        }

        T[] oldData = (T[]) dest.toArray();
        int length = oldData.length;
        for (T t : src) {
            Integer index = map.get(t);
            if (index != null) {
                oldData[index] = null;
                length--;
            }
        }

        T[] removedDuplicate = (T[]) new Object[length];
        int index = 0;
        for (int i = 0; i < oldData.length; i++) {
            if (oldData[i] != null) {
                removedDuplicate[index++] = oldData[i];
            }
        }

        dest.clear();
        dest.addAll(Arrays.asList(removedDuplicate));
    }
}

Related

  1. addFirst(List list, Object values)
  2. cons(P first, List list)
  3. equalLists(List first, List second)
  4. expectedOrder(List src, Object first, Object second)
  5. extractFirst(int numberToExtract, List list)

  6. HOME | Copyright © www.java2s.com 2016