Java流过滤特定索引的项目 [英] Java stream filter items of specific index

查看:87
本文介绍了Java流过滤特定索引的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 列表中的索引,然后将这些索引映射到其中的相应元素list(更好的方法是为索引设置 HashSet< Integer> ,因为它们按定义是唯一的,因此包含是一个恒定时间操作。)

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流过滤特定索引的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆