特定索引的Java流过滤项

2022-01-22 00:00:00 java-8 java java-stream

我正在寻找一种简洁的方法来过滤列表中特定索引处的项目.我的示例输入如下所示:

I'm looking for a concise way to filter out items in a List at a particular index. My example input looks like this:

List<Double> originalList = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
List<Integer> filterIndexes = Arrays.asList(2, 4, 6, 8);

我想过滤掉索引 2468 处的项目.我有一个 for 循环跳过与索引匹配的项目,但我希望有一种使用流的简单方法来完成它.最终结果如下所示:

I want to filter out items at index 2, 4, 6, 8. I have a for loop that skips items that match the index but I was hoping there would be an easy way of doing it using streams. The final result would look like that:

List<Double> filteredList = Arrays.asList(0.0, 1.0, 3.0, 5.0, 7.0, 9.0, 10.0);

推荐答案

您可以生成一个 IntStream 来模仿原始列表的索引,然后删除 filteredIndexes 中的索引 列表,然后将这些索引映射到列表中的相应元素(更好的方法是为索引设置一个 HashSet,因为它们在定义上是唯一的,因此 contains 是一个常数时间操作).

You can generate an IntStream to mimic the indices of the original list, then remove the ones that are in the filteredIndexes list and then map those indices to their corresponding element in the list (a better way would be to have a HashSet<Integer> for indices since they are unique by definition so that contains is a constant time operation).

List<Double> filteredList = 
    IntStream.range(0, originalList.size())
             .filter(i -> !filterIndexes.contains(i))
             .mapToObj(originalList::get)
             .collect(Collectors.toList());

相关文章