Java stream filter items of specific index(特定索引的Java流过滤项)
问题描述
我正在寻找一种简洁的方法来过滤列表中特定索引处的项目.我的示例输入如下所示:
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);
我想过滤掉索引 2
、4
、6
、8
处的项目.我有一个 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());
这篇关于特定索引的Java流过滤项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:特定索引的Java流过滤项


- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01