Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get certain String values in an array in java

Tags:

java

arrays

String [] array=new String[7];

array[0]="a";
array[1]="b";
array[2]="c";
array[3]="d";
array[4]="e";
array[5]="f";
array[6]="g";

for (int i=0;i<array.Length;i++){
  if(array[i].equals("b")) {
        // check array from the first one and when it is "b" starts
        // to print the string value till "e"
        System.out.println(array[i]);
    }
    if (array[i].equals("e"))
        break;
}

I have an array of Strings and i want to print the the all the string values when it hits "b" and stop at "e"

Is there anyway i can do that ?

My expected outcome is :

b
c
d
e
like image 281
Jason WEI Avatar asked Nov 30 '25 11:11

Jason WEI


2 Answers

A Java-9 solution would be:

Arrays.stream(array)
      .dropWhile(e -> !"b".equals(e))
      .takeWhile(e -> !"f".equals(e))
      .forEach(System.out::println);
like image 200
Ousmane D. Avatar answered Dec 02 '25 02:12

Ousmane D.


List<String> list = Arrays.asList(array);

list.subList(list.indexOf("b"), list.indexOf("e") + 1)
    .forEach(System.out::println);

*assuming that both "b" and "e" are present in the array (1) and "e" comes after "b" (2).

like image 43
Andrew Tobilko Avatar answered Dec 02 '25 00:12

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!