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]