Java 相当于 Python 的切片

标签 java python java-8 java-stream

<分区>

如您所知 - 如果没有,请查看 here - Python 的切片 : 表示法执行以下操作

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
a[-1] last item in the array
a[-2:] last two items in the array
a[:-2] everything except the last two items

我想知道它是通过 Java 流还是类似更新的标准 API 中的其他东西实现的,因为它有时真的很有用。

最佳答案

您可以使用 IntStream.range API如下:

[1:5] 相当于“从1到5”(不包括5)

IntStream.range(1, 5).mapToObj(list::get)
            .collect(Collectors.toList());

[1:]等同于“1到结束”

IntStream.range(1, list.size()) // 0 not included

a[-1] 数组中的最后一项

IntStream.range(list.size() - 1, list.size()) // single item

a[-2:] 数组中的最后两项

IntStream.range(list.size() - 2, list.size()) // notice two items

a[:-2] 除了最后两项之外的所有内容

IntStream.range(0, list.size() - 2)

注意参数在上下文range (int startInclusive, int endExclusive)中。

给定一个整数列表

List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);

完成上述任何一项以获得切片将类似于指定

List<Integer> slice = IntStream.range(1, 5).mapToObj(list::get)
            .collect(Collectors.toList()); // type 'Integer' could depend on type of list

您还可以使用另一个 API 实现类似的功能 List.subList具有类似的构造,例如

List<Integer> subList = list.subList(1, 5);

以上都会输出

[2, 3, 4, 5]

关于Java 相当于 Python 的切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470966/

相关文章:

java - 如何在冒号分隔的字符串中查找最后 2 项的字符串

java - 空对象引用上的 Location.getLatitude()

java - Nutch + Solr - 索引器导致 java.lang.OutOfMemoryError : Java heap space

python - 如何使用表示 matplotlib 中的原始数据的颜色条绘制对数归一化 imshow 图

python - 值错误 : could not convert string to float: id

java - IntelliJ IDEA 2017.1.3 给出错误 - 未定义项目 SDK,即使将项目 SDK 设置为 Java 1.8 JDK

java - 文件上传无法通过java代码在jenkins中工作

java - 通过omnifaces ViewScoped多次调用PreDestroy方法

python - 变量的赋值

java - 实现封装的正确方法