-2

I have an String arraylist with the following content:

[0] = "ID: 12"
[1] = "Term: Banana"
[2] = "Definition = yellow fruit"
[3] = "ID: 14"
[4] = "Term: Apple"
[5] = "Definition = green fruit"
[6] = "Description = Beautiful fruit"
[7] = "ID: 16"
[8] = "Term: Melon"
[9] = "Definition = yellow fruit"

I only need the output from ID to the next ID.

For example:

Term: Apple
Definition = green fruit
Description = Beautiful fruit

How can I access it without specifying the exact location. I thought of contains("ID") until the next contains("ID"), I just don't know how to implement it.

Thank you very much for your help

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 10
    By the looks of it your main problem is that saving your data in that structure (a list of strings) isn't a very good idea. Have you considered creating a custom class that holds all this data (ID, Term and definition) and working with objects of that class instead of just plain strings? – OH GOD SPIDERS Dec 06 '21 at 14:49
  • 4
    Maybe you should consider taking the [tour]? (You get the _Informed_ badge after you do.) I see that your [other question](https://stackoverflow.com/questions/70185249/string-print-out-specific-rows) got a few down-votes. May be a good idea to read advice on [how to ask](https://stackoverflow.com/help/how-to-ask). – Abra Dec 06 '21 at 14:58

2 Answers2

0

i thing you should use collection objects in the array instead of string as it is.it allows you to collect your desired data in the order you want.

0

If you do not need to print IDs, you can just filter them out by using String::startsWith:

List<String> data = Arrays.asList(
    "ID: 12", "Term: Banana", "Definition = yellow fruit",
    "ID: 14", "Term: Apple", "Definition = green fruit", "Description = Beautiful fruit",
    "ID: 16", "Term: Melon", "Definition = yellow fruit"
);

for (String item : data) {
    if (item != null && !item.startsWith("ID:")) {
        System.out.println(item);
    } else { // optionally print empty line to separate items
        System.out.println();
    }
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42