Home > front end >  Arraylist Output
Arraylist Output

Time:12-07

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

CodePudding user response:

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.

CodePudding user response:

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();
    }
}

CodePudding user response:

is this your mean?

public static void main(String[] args){
        List<String> strList = new ArrayList<>();

        strList.add("ID: 12");
        strList.add("Term: Banana");
        strList.add("Definition = yellow fruit");
        strList.add("ID: 14");
        strList.add("Term: Apple");
        strList.add("Definition = green fruit");
        strList.add("Description = Beautiful fruit");
        strList.add("ID: 16");
        strList.add("Term: Melon");
        strList.add("Definition = yellow fruit");

        StringBuilder sb = null;
        for (String str: strList){
            if(str.startsWith("ID: ")){
                if (null != sb){
                    String term = sb.toString();
                    System.out.println(term);
                }
                sb = new StringBuilder();
                continue;
            }
            sb.append(str   "\n");
        }

        if (null != sb){
            String term = sb.toString();
            System.out.println(term);
        }
    }
  • Related