user2057437
user2057437

Reputation: 81

How to list the objects of rdf statements?

I would like to select a list of the resources related to a given subject resource, via any RDF predicate.

For example, if the resources in my model are ex:alice, ex:bob, ex:peter and ex:Ben, and my model contains:

ex:alice ex:meet ex:bob.  
ex:alice foaf:knows ex:Peter.  
ex:alice ex:talk :ben.  

How would I write a method to return list of resources, which are the objects of any triple given a particular resource as the subject? For example, if I give:

resourcesRelatedToResource( alice );

I expect a list containing Bob, Peter, and Ben.

Upvotes: 2

Views: 1307

Answers (1)

Ian Dickinson
Ian Dickinson

Reputation: 13305

Using the Jena API, if you call listStatements with a null argument for the subject, object or predicate that will act as a wild-card. So you want to just pass the subject Alice, and collect the objects of the matching triples if they are objects. Jena has a short-cut for that: given a resource r, the call:

r.listProperties()

is equivalent to:

r.getModel().listStatements( r, null, (RDFNode) null )

So:

public void test() {
    Model m = /*... your model here ...*/;

    // get a reference to the Alice resource
    Resource alice = m.getResource( NS + "alice" );

    Set<Resource> result = resourcesRelatedToResource( alice );
}

/** Return a set of the resources related to the given input 
  * resource via any predicate */
protected Set<Resource> resourcesRelatedToResource( Resource r ) {
    // we don't care about duplicates, so use a Set
    Set<Resource> objs = new HashSet<Resource>();

    // iterate over the triples with alice as subject
    for (StmtIterator i = r.listProperties(); i.hasNext(); ) {
        RDFNode obj = i.nextStatement().getObject();

        if (obj.isResource()) {
            objs.add( obj.asResource() );
        }
    }

    return objs;
}

Upvotes: 2

Related Questions