How can I print all array elements after a specific one in Java?

Viewed 199

Let's suppose I have an array String args[] with a certain amount of elements.
Let's say it goes to up to args[100]. I want to print all the elements of args[] above args[5]. I don't want to do System.out.println(args[6] + args[7] + args[8] + args[9] + args[10]); and etc and etc. I was wondering if there is a cleaner and more efficient way to print all of those array elements.
Thanks.

4 Answers

You can use a simple for-loop:

for(int i = 6; i < args.length; i++) System.out.print(args[i]);

You need a loop.

In your case, assuming a modern JDK I'd use stream and lambdas:

Arrays.stream(arr)
  .skip(5)
  .forEach(System.out::println);

For loop, probably the most common, certainly in older codebases without lambdas and streaming:

    for(int i = 5; i< arr.length; i++) {
        System.out.println(arr[i]);
    }

You can use IntStream#range as shown below:

IntStream.range(5, arr.length).forEach(i -> System.out.print(arr[i]));

Demo:

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        String arr[] = { "a", "b", "c", "d", "e", "f", "g" };
        IntStream.range(2, arr.length).forEach(i -> System.out.print(arr[i]));
    }
}

Output:

cdefg

You can use dropWhile method that returns:

...a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.

Example:

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

Arrays.stream(arr).dropWhile(i -> i != 5).forEach(System.out::print); // 56789
Related