Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array to list with specific range in Java 8

Tags:

java

java-8

I want to convert one string array to list with specific range. In my case I always want from index 1 to last index. I don't need the index 0 value included in the list. Is there any direct method that I can use to filter and convert to the list as I need ?

public class test1 {

    public static void main(String[] args) {
        String[] optArr = {"start", "map1", "map2", "map3"};
        List<String> list = Arrays.stream(optArr).collect(Collectors.toList());
        System.out.println(list);
    }
}
like image 879
Prasad Avatar asked Dec 27 '18 06:12

Prasad


2 Answers

You can use Stream.skip():

List<String> list = Arrays.stream(optArr).skip(1).collect(Collectors.toList());
like image 196
Robby Cornelissen Avatar answered Oct 16 '22 05:10

Robby Cornelissen


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);
like image 45
Naman Avatar answered Oct 16 '22 03:10

Naman