【问题标题】:Java equivalent of Python's slice [duplicate]Java相当于Python的切片[重复]
【发布时间】:2019-04-27 11:58:54
【问题描述】:

如您所知 - 如果没有,请查看 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 中类似的其他东西实现的较新,因为它有时真的很有用。

【问题讨论】:

  • 它太宽泛了,而且是 5 个不同的问题。不清楚您所说的“或其他”是什么意思。
  • 在标准 API 中没有这样的东西,但我想实现起来并不复杂,但您必须将 :-2 部分作为字符串传递并解析它
  • @Eugene 对于所有用例,IntStream.range 怎么样?我的意思不是语法而是功能。
  • @nullpointer 对,但您仍然需要解析该输入,我猜它也可以通过多种其他方式完成
  • -i作为python中的索引与len(array)-i相同,所以用Java实现很简单。

标签: java python java-8 java-stream


【解决方案1】:

您可以按如下方式使用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]

【讨论】:

  • 这是假设您也不是在寻找解析功能,例如要解析的a[:-2]
  • 我认为他也想从数组中获取值,而不仅仅是生成值。
  • @Andrei 是的,完全正确
  • @snr 以您可能正在寻找的内容为例进行了更新。
猜你喜欢
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 2013-04-28
  • 2013-09-22
  • 2017-06-25
相关资源
最近更新 更多