Miqhtie
Miqhtie

Reputation: 73

How to print out array index 2-5

I was creating a program that had an array involved and at one point I wanted to print out part of the array. I wanted to know how to print out for example array indexes 2-5.

I tried doing something like this but it didn't work.

String[] testArray = {"a", "b", "c", "d", "e", "f'", "g"};
System.out.println(testArray[2,5]);

but it didn't work. (not that I fully expected it too).

I was just wondering how you would do something like this.

Upvotes: 2

Views: 2540

Answers (5)

Mohammed Deifallah
Mohammed Deifallah

Reputation: 1330

You have 2 options:

1) Using Arrays.copyOfRange() method.

2) If you're using Java8, then you can use streams to do your job as follows:

int[] slice = IntStream.range(2, 5)
                        .map(i -> testArray[i])
                        .toArray(); 

Upvotes: 0

Muzzamil
Muzzamil

Reputation: 2881

You can use System.arraycopy here is java documentation

// copies elements 2 and 5 from sourceArray to targetArray

    System.arraycopy(sourceArray, 2, targetArray, 0, 4);

OR

Wrap your array as a list, and request a sublist of it.

MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(startIndex, endIndex);

Upvotes: 0

A. Wolf
A. Wolf

Reputation: 1347

If you want to print array element from index 2 to index 5:

public void printArrayInIndexRange(String[] array, int startIndex, int endIndex) {
      for(int i = startIndex; i < endIndex && i < array.length; i++) {
          System.out.println(array[i]);
      }       
}

Then simply call the method:

printArrayInIndexRange(testArray, 2, 5);

Note: the condition i < array.length helps to avoid IndexOutOfBoundException.

Upvotes: 0

deHaar
deHaar

Reputation: 18568

You can do it in a loop:

for (int i = 2; i < 6; i++) {
    System.out.println(testArray[i]);
}

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59986

You can use Arrays::copyOfRange, like this :

Arrays.copyOfRange(testArray, 2, 5)

To print the result, you can use :

System.out.println(Arrays.toString(Arrays.copyOfRange(testArray, 2, 5)));

Outputs

[c, d, e]

Upvotes: 5

Related Questions