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流过滤项
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01