Convert an array to list with specific range in Java 8
You can also use the overloaded method Arrays.stream(T[] array, int startInclusive, int endExclusive)
as :
List<String> list = Arrays.stream(optArr, 1, optArr.length)
.collect(Collectors.toList());
Returns a sequential Stream with the specified range of the specified array as its source.
Alternatively(non Java-8), using the subList
is an option, but I would prefer chaining it in one-line instead of creating a new object as:
List<String> list = Arrays.asList(optArr).subList(1, optArr.length);
One non Java 8 option might be to just create a view on top of your current list which omits the first element:
List<String> list = Arrays.stream(optArr).collect(Collectors.toList());
List<String> viewList = list.subList(1, list.size());
This would mean though that the underlying data structure is still the original list, but one extra element in memory does not seem like a big penalty.
You can use Stream.skip()
:
List<String> list = Arrays.stream(optArr).skip(1).collect(Collectors.toList());