How to store Sparql query results into array?

I want to store my sparql query results into array. How can i store it? This is my java code. Is it possible using datareader in java?

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.util.FileManager;

public class emotion{
public static void main(String[] args) {
    // TODO Auto-generated method stub

sparqltest();}


static void sparqltest()
{

FileManager.get().addLocatorClassLoader(emotion.class.getClassLoader());
Model model= FileManager.get().loadModel("C:/Users/avg/workspacejena32/Jena/bin/emotion.rdf");
//System.out.println("Connected...");
String queryString="PREFIX  xsd:  <http://www.semanticweb.org/avg/ontologies/2016/2/untitled-ontology-5#>" +
                   "PREFIX  owl:  <http://www.w3.org/2002/07/owl#>" +
                   "PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" +
                   "SELECT  * " +
                   "WHERE" +
                   "{ xsd:angry xsd:says ?x}";




 Query query= QueryFactory.create(queryString);
 QueryExecution qexec=QueryExecutionFactory.create(query, model);

 try {
 ResultSet rs = qexec.execSelect();
for ( ; rs.hasNext() ; )
{
  QuerySolution soln = rs.nextSolution() ;
  RDFNode a = soln.get("x") ;
 // avg = a.asNode().getLocalName();
  System.out.println(a.asNode().getLocalName());
}
} 
 finally {

 qexec.close();
    }}}

i am getting results as follows which i want to store in array or something else from where i can call that one by one for future use.

selfish
mad

Upvotes: 0

Views: 1366

Answers (1)

Natan Cox
Natan Cox

Reputation: 1545

Something like this should do it.

List<RDFNode> result = new ArrayList<RDFNode>();
ResultSet rs = qexec.execSelect();
for ( ; rs.hasNext() ; )
{
  QuerySolution soln = rs.nextSolution() ;
  RDFNode a = soln.get("x") ;
 // avg = a.asNode().getLocalName();
  System.out.println(a.asNode().getLocalName());
  result.add(a);
}

Upvotes: 2

Related Questions