Java List Select select(List list, List indices, List sel)

Here you can find the source of select(List list, List indices, List sel)

Description

select

License

BSD License

Declaration

public static <E> List<E> select(List<E> list, List<Integer> indices, List<E> sel) 

Method Source Code

//package com.java2s;
// Licensed under the Modified BSD Licence; see COPYING for details.

import java.util.Iterator;

import java.util.List;

public class Main {
    public static <E> List<E> select(List<E> list, List<Integer> indices, List<E> sel) {
        Iterator<Integer> itIndex = indices.iterator();
        if (!itIndex.hasNext()) {
            return sel;
        }/*www . ja  v a  2  s  .  c  o m*/
        int desiredIndex = itIndex.next().intValue();

        // Resulting list (to be filled in with selected elements).
        int currIndex = 0;
        for (E elem : list) {
            if (currIndex == desiredIndex) {
                // It is possible to select the same element multiple times;
                // indices may contain duplicates, e.g., [2, 4, 4, 10] .
                while (currIndex == desiredIndex) {
                    sel.add(elem);
                    if (!itIndex.hasNext())
                        return sel;
                    desiredIndex = itIndex.next().intValue();
                }
                if (desiredIndex < currIndex)
                    throw new Error("List of indices should be non-decreasing; instead, " + indices);
            }
            currIndex++;
        }
        // if we arrive here, it must be that there are still unused indices
        throw new Error("Not enough elements in the 1st list arg; list = " + list + "\n\tindices = " + indices);
    }
}

Related

  1. select(List src, List indexes)
  2. selectDuplicateQualifiers( List elements)
  3. selectElements(final List list, int start, int end)
  4. selectExactly(List original, int nb)