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
A Java-9 solution would be:
Arrays.stream(array)
.dropWhile(e -> !"b".equals(e))
.takeWhile(e -> !"f".equals(e))
.forEach(System.out::println);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With