How do I print out only the first 3 elements of an array that has 5 elements in java?

33,256

Solution 1

Print first 25 elements:

for (int i=0; i<25; i++) {
    System.out.println(strArray[i]);
}

Print element number 10 to 50:

for (int j=9; j<50; j++) {
    System.out.println(strArray[j]);
}

Solution 2

Since Java 8

You can use limit from the Stream class:

Stream.of(strArray).limit(3).forEach(System.out::println);

or

Arrays.stream(strArray).limit(3).forEach(System.out::println); 

Solution 3

You can do this very easily using a for loop

String[] strArray = {"bacon", "chicken", "ham", "egg", "poop"};
for (i = 0; i < 3; i ++){
    Ssytem.out.println(strArray[i]);
};
Share:
33,256
Max Echendu
Author by

Max Echendu

Updated on July 06, 2022

Comments

  • Max Echendu
    Max Echendu almost 2 years

    How do I only print out the first 5 elements of an array that has 10 elements?

    I know I can just do:

    String[] strArray = {"bacon", "chicken", "ham", "egg", "poop"};
    System.out.println(strArray[0]);
    System.out.println(strArray[1]);
    System.out.println(strArray[2]);
    

    But assuming I had 100 elements and wanted to print out the first 25 elements. Or wanted to print out all elements from the 10th to the 50th. Writing all the lines of code would take up time.

    Is there like a way to tell the console to print "from" one element to another? Sort of like from 10-50? So like a short-cut.

    • Nir Alfasi
      Nir Alfasi almost 9 years
      Hint: for-loop
    • Alp
      Alp almost 9 years
      read about loops. for loop is your friend. java.util.Arrays.sort() is good to sort arrays and it is your friend as well. =]