从索引创建子列表

Creating sublist from indices

是否可以仅使用元素索引从另一个列表创建子列表? 我正在寻找好的解决方案,例如lambda,来自 Java 8.

的流

例如(伪代码):

a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
b = a.getByIndices([0, 2, 4, 5, 3])
print(b) // [10, 8, 6, 5, 7]

你可以有以下方法:

private static <T> List<T> getByIndices(List<T> list, List<Integer> indexes) {
    return indexes.stream().map(list::get).collect(toList());
}

这会根据给定的索引创建一个 Stream,映射到索引处的列表元素并将结果收集到列表中。

示例用法:

List<Integer> list = Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
List<Integer> indexes = Arrays.asList(0, 2, 4, 5, 3);
System.out.println(getByIndices(list, indexes)); // prints [10, 8, 7, 6, 5]

对于整数数组,你可以使用这个:

int[] b = IntStream.of(0, 2, 4, 5, 3)
      .map(i -> a[i])
      .toArray();

扩展 AbstractList is a quick way to get a list implementation up and running. Like the regular List.subList 方法,以下子列表由主列表支持,因此对子列表的更改将写入主列表(这可能是也可能不是您想要的功能,但您可以如果需要,总是从子列表中创建一个新的、单独的 ArrayList)。未实现通过子列表删除元素;这是可行的,但需要更多的工作。

public static <E> List<E> sublistFromIndices(List<E> list, int... indices) {
    Objects.requireNonNull(list);
    Objects.requireNonNull(indices);
    return new AbstractList<E>() {
        @Override
        public int size() {
            return indices.length;
        }

        @Override
        public E get(int index) {
            return list.get(indices[index]);
        }

        @Override
        public E set(int index, E element) {
            return list.set(indices[index], element);
        }
    };
}

我写了这个函数来完成你的要求。我不知道如何让它成为 lambda 函数,但我会继续努力。

public static <E> void createSublist(List<E> oldList, List<E> newList, int[] indicies){
        for(int i = 0; i < indicies.length; i++)
             newList.add(oldList.get(indicies[i]));} //Adds indicies to new list