user5721551
user5721551

Reputation:

Split an arraylist of strings to its original strings elements

So I have this Arraylist:

ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < arr1.length(); i++) {
JSONObject objectt = arr1.getJSONObject(i);
JSONObject triple = objectt.getJSONObject("triple");
String subject=triple.getString("s");
String predicate=triple.getString("p");
String value=triple.getString("o");
al.add(subject);
al.add(predicate);
al.add(value);
}

I wanna know if there is a way to split the arraylist "al" into the original strings (subject, predicate, value) outside the for loop?

Upvotes: 0

Views: 43

Answers (1)

David Conrad
David Conrad

Reputation: 16399

Don't store the individual strings separately, store them in an object that has fields for subject, predicate, and value, like this:

public class Triple {
    private String subject;
    private String predicate;
    private String value;

    public Triple(String subject, String predicate, String value) {
        this.subject = subject;
        this.predicate = predicate;
        this.value = value;
    }

    /* getters, toString, equals and hashCode if necessary... */
}

// . . .
    List<Triple> al = new ArrayList<>();
    for (int i = 0; i < arr1.length(); i++) {
        JSONObject triple = arr1.getJSONObject(i).getJSONObject("triple");
        String subject = triple.getString("s");
        String predicate = triple.getString("p");
        String value = triple.getString("o");
        al.add(new Triple(subject, predicate, value));
    }

Then, if you want to use the values, call the getters:

// . . .
    for (Triple t : al) {
        String subject = t.getSubject();
        String predicate = t.getPredicate();
        String value = t.getValue();
        // do something with them
    }

Upvotes: 1

Related Questions