如您所知 - 如果没有,请查看 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]