2

As you know - if not, glance at here - Python's slice : notation does the following

[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

I wonder that whether it is achieved by Java streams or something else in standard APIs similar newer since it is really useful sometimes.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
  • 1
    It's too broad, and it's 5 different questions. It's unclear what you meant by "or something else". – Andrew Tobilko Nov 25 '18 at 19:16
  • nothing in the standard API like this, but I guess it's not that complicated to implement, but you will have to pass `:-2` part as a String and parse it – Eugene Nov 25 '18 at 19:17
  • @Eugene how about `IntStream.range` for all the use cases? I mean not the syntax but functionality. – Naman Nov 25 '18 at 19:20
  • @nullpointer right, but you would still need to parse that input, it could be done in multiple other ways too, I guess – Eugene Nov 25 '18 at 19:21
  • `-i` as an index in python is the same as `len(array)-i`, so is straightforward to implement with Java. – cs95 Nov 25 '18 at 19:26
  • @Eugene I don't think OP is asking for that exact syntax (to be parsed). The question is about whether there's an equivalent in Java. – sprinter Nov 25 '18 at 19:34
  • @sprinter as said earlier - *nothing in the standard API like this*... – Eugene Nov 25 '18 at 19:35

1 Answers1

1

You can possibly use the IntStream.range API as follows :

[1:5] is equivalent to "from 1 to 5" (5 not included)

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

[1:] is equivalent to "1 to end"

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

a[-1] last item in the array

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

a[-2:] last two items in the array

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

a[:-2] everything except the last two items

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

Notice the arguments are in the context range​(int startInclusive, int endExclusive).

Given a list of integer

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

Completing any of the above to get the slice would be similar to specifying

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

You can also attain something similar using another API List.subList with a similar construct, for e.g.

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

Both the above would output

[2, 3, 4, 5]
Naman
  • 27,789
  • 26
  • 218
  • 353