ID| TOPIC | TITLE | TYPE | NAME |
---------------------------------
1 | AB | BCD | ref | Ferari|
----------------------------------
1 | AB | BCD | ref | TOYOTA|
----------------------------------
1 | AB | BCD | ref| AUDI |
----------------------------------
1 | AB | BCD | ref| BMW |
---------------------------------
2 | BC | ABC | ref | NISSAN|
----------------------------------
2 | BC | ABC | ref | SUZKI|
----------------------------------
2 | BC | ABC | ref| TATA |
Cursor hold data like this table. Now, I want get data like ID| TOPIC | TITLE | TYPE | NAME | here NAME can be multiple according to the ID. Like for ID 1 K will be FERARI,TOYOTA,AUDI,BMW and so on. I want to show this information in customlistview in a row .
My question is
is there any way to store the name data in String Array or do you have any alternative suggestion for me
If I understand your question correctly, you want to store your values from your database table in arrays? For that, you could create parallel resizeable generic lists like this:
ArrayList<int> ids = new ArrayList<int>();
ArrayList<String> topics = new ArrayList<String>();
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> names = new ArrayList<String>();
And you can then add items to it like this:
ids.add(cursor.getInt(cursor.getColumnIndexOrThrow("_id")));
topics.add(cursor.getString(cursor.getColumnIndexOrThrow("TOPIC")));
titles.add(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
types.add(cursor.getString(cursor.getColumnIndexOrThrow("TYPE")));
names.add(cursor.getString(cursor.getColumnIndexOrThrow("NAME")));
P.S. your database looks wrong - values in ID column should be unique, if ID is the primary key (it looks like it should be).
P.S.P.S
Another option would be to use Object-Oriented design - Create a class that has members like id, topic, title, type, name and so on.
public class Product {
private int id;
private String topic;
private String title;
private String type;
private String name;
public Product(Cursor cursor) {
this.id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
this.topic = cursor.getString(cursor.getColumnIndexOrThrow("TOPIC"));
this.title = cursor.getString(cursor.getColumnIndexOrThrow("TITLE"));
this.type = cursor.getString(cursor.getColumnIndexOrThrow("TYPE"));
this.name = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
}
//Getter & Setter here...
}
this Product could be in a list of Products like:
ArrayList<Product> products = new ArrayList<Product>();
Product product = new Product(cursor);
products.add(product); // or simpler: products.add(new Product(cursor);
and you could use this list for many purposes like:
ArrayList<int> ids = new ArrayList<int>();
ArrayList<String> topics = new ArrayList<String>();
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> names = new ArrayList<String>();
for (Product product : products) {
// for every product in your products list do:
ids.add(product.getId);
topics.add(product.getTopic);
titles.add(product.getTitle);
types.add(product.getType);
names.add(product.getName);
}
Related
I have a dataFrame like the following:
+-----------------+--------------------+
| id| document|
+-----------------+--------------------+
| doc1 |"word1, word2" |
| doc2 |"word3 word4" |
+-----------------+--------------------+
I want to create another dataFrame with following structure:
+-----------------+--------------------+-----------------+
| id| document| word |
+-----------------+--------------------+----------------|
| doc1 |"word1, word2" | word1 |
| doc1 |"word1 word2" | word2 |
| doc2 |"word3 word4" | word3 |
| doc2 |"word3 word4" | word4 |
+-----------------+--------------------+----------------|
I tried the following:
public static Dataset<Row> buildInvertIndex(Dataset<Row> inputRaw, SQLContext sqlContext, String id) {
JavaRDD<Row> inputInvertedIndex = inputRaw.javaRDD();
JavaRDD<Tuple3<String, String ,String>> d = inputInvertedIndex.flatMap(x -> {
List<Tuple3<String, String, String>> k = new ArrayList<>();
String data2 = x.getString(0).toString();
String[] field2 = x.getString(1).split(" ", -1);
for(String s: field2)
k.add(new Tuple3<String, String, String>(data2, x.getString(1), s));
return k.iterator();
}
);
JavaPairRDD<String, Tuple2<String, String>>d2 = d.mapToPair(x->{
return new Tuple2<String, Tuple2<String, String>>(x._3(), new Tuple2<String, String>(x._1(), x._2()));
});
Dataset<Row> d3 = sqlContext.createDataset(JavaPairRDD.toRDD(d2), Encoders.tuple(Encoders.STRING(), Encoders.tuple(Encoders.STRING(),Encoders.STRING()))).toDF();
return d3;
}
But it gives:
+-----------------+----------------------+
| _1| _2 |
+-----------------+----------------------+
| word1 |[doc1,"word1, word2"] |
| word2 |[doc1,"word1 word2"] |
| word3 |[doc2, "word3, word4"]|
| word4 |[doc2, "word3, word4"]|
+-----------------+----------------------+
Im newbie to spark in java. SO please any help will be so appreciated. In addition please, suppose in the second dataframe above i want to compute a string similarity metric(i.e, jaccard) on the two column document and word and add the result in a new column, how can i do that?
You can use explode and split
import static org.apache.spark.sql.functions.expr;
inputRaw.withColumn("word", expr("explode(split(document, '[, ]+'))"))
I have a string array of student info:
StudentNumber Integer, Subject String, mmarks integer
What would be the best way to use the java & collection to find out the topper in each subject.
ArrayList<String> strings = new ArrayList<String>();
strings.add("1 | Computers | 48");
strings.add("2 | Data Structures | 89");
strings.add("33 | English | 35");
strings.add("24 | Maths | 70");
strings.add("15 | Computers | 58");
strings.add("6 | Data Structures | 55");
strings.add("7 | English | 40");
strings.add("18 | Maths | 73");
for (String str : strings) {
String [] strArray = str.split("\\|");
// in completed code
for (int i = 0; i < str.length(); i++) {
sam.put(strArray[0], strArray[2]);
s.add(strArray[1]);
}
}
Expected output
15 Computers
2 Data structures
7 English
18 Maths
Create a Result class to store the information:
class Result {
private int studentNumber;
private String subject;
private int mark;
// constructor, getters and setters go here ...
}
Now convert your List<String> to a List<Result>:
List<Result> results = new ArrayList<>();
for (String s : strings){
String[] sa = s.split(" \\| ");
results.add(new Result(Integer.parseInt(sa[0]), sa[1], Integer.parseInt(sa[2])));
}
Create a stream from the results list, group by subject, and find the student with the highest mark:
Map<String, Integer> map = results.stream()
.collect(Collectors.groupingBy(Result::getSubject,
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Result::getMark)), r -> r.get().getStudentNumber())));
Print the result:
map.forEach((k,v) -> System.out.println(v + " " + k));
15 Computers
18 Maths
7 English
2 Data Structures
I have a table with 5 columns (id |state_abbrevation | state_name | area_code | cities ). I have to store all the values as key value pair where key= state_abbrevation and Value = (area_code) cities.
Also state_abbrevation has duplicates. A sample data is shown below:
id | state_abbrevation | state_name | area_code | cities
----+-------------------+--------------+-----------+---------------------
1 | AK | Alaska | 907 | Juneau
2 | AL | Alabama | 205 | Birmingham
3 | AL | Alabama | 251 | Mobile
4 | AL | Alabama | 256 | Huntsville
5 | AL | Alabama | 334 | Montgomery
6 | AL | Alabama | 938 | Florence/Huntsville
7 | AR | Arkansas | 479 | Ft. Smith
8 | AR | Arkansas | 501 | Little Rock
9 | AR | Arkansas | 870 | Jonesboro
10 | AZ | Arizona | 480 | Scottsdale
11 | AZ | Arizona | 520 | Tucson
12 | AZ | Arizona | 602 | Phoenix
13 | AZ | Arizona | 623 | Glendale
14 | AZ | Arizona | 928 | Flagstaff
15 | CA | California | 209 | Modesto
16 | CA | California | 213 | Los Angeles
17 | CA | California | 310 | West Hollywood
18 | CA | California | 323 | Hollywood
What's the best solution to store in key value pair where key = AL & Value = Area code and City for all state_abbrevation= AL.
Example for Hashmap I want:
KEY, VALUE
AK, (907) Juneau
AL, (205) Birmingham
(251) Mobile
(256) Huntsville
(938) Florence
.......and so on.
Here's my working code using Hibernate:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
public class HibernateCriteriaExamples {
public static void main(String[] args) {
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(State.class);
//List<State> stateList = criteria.list();
List<String> stateAbbrevationList = criteria.setProjection(Projections.distinct(Projections.property("stateAbbrevation"))).list();
HashMap<String,List> cityAreacodeAndState = new HashMap<String,List>();
for(int i=0; i<stateAbbrevationList.size();i++)
{
String abbrevation = stateAbbrevationList.get(i);
//System.out.println(abbrevation);
Criteria criteriaareaCodeWithCity = session.createCriteria(State.class);
List<State> stateObject = criteriaareaCodeWithCity.add(Restrictions.eq("stateAbbrevation", abbrevation)).list();
List<String> formattedAreaCodeAndCity =new ArrayList<String>();
for(int j=0; j<stateObject.size();j++)
{
State state = (State)stateObject.get(j);
int a = state.getAreacode();
String b = state.getCities();
String c = "("+a+") "+b;
// System.out.println(c);
formattedAreaCodeAndCity.add(c);
}
cityAreacodeAndState.put(abbrevation, formattedAreaCodeAndCity);
}
System.out.println("---------------PRINTING REQUIRED DATA------------------");
for (HashMap.Entry<String,List> formattedAreaCodeAndCity1 : cityAreacodeAndState.entrySet())
{
System.out.println(formattedAreaCodeAndCity1.getKey() + "," + formattedAreaCodeAndCity1.getValue());
}
tx.commit();
sessionFactory.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You can use HashMap as well as List.
Your HashMap key will be state_abbrevation and your value (i.e., List) will contain area_code and cities.
HashMap<String, List<String>> data = new HashMap<>();
..
while(rs.next()) {
List<String> temp = new ArrayList<>();
temp.add(rs.getString("area_code"));
temp.add(rs.getString("cities"));
data.put(rs.getString("state_abbrevation"), temp);
}
to get the data related to state CA
data.get("CA").get(0) // -> gives area_code related to state "CA"
data.get("CA").get(1) // -> gives cities related to state "CA"
As was mentioned in comments, you can use value object to keep data for state:
public Map<String, State> getStatesMap() {
... execute query and get resultSet
Map<String, State> result = new HashMap<>();
while (resultSet.next()) {
result.put(
resultSet.getString("state_abbrevation"),
new State(
resultSet.getString("area_code"),
resultSet.getString("cities")
)
);
}
return result;
}
private class State {
private final String area;
private final String cities;
public State(String area, String cities) {
this.area = area;
this.cities = cities;
}
public String getArea() {
return area;
}
public String getCities() {
return cities;
}
}
I am getting an empty result set when I try to retrieve the data stored in a jena model.
This is the code to load the data (I have removed the imports for brevity)
package basic;
//imports here
public class DataLoaderQn {
public static void main(String[] args) throws FileNotFoundException {
String resourceURI = "http://www.abc123.com/riskmodelling/static/risks";
String directory = "D:/mywork/dp/projs/static-risks/data/test";
Dataset dataset = TDBFactory.createDataset(directory);
Model model = null;
try {
dataset.begin(ReadWrite.WRITE);
model = dataset.getDefaultModel();
model.enterCriticalSection(Lock.WRITE);
model = model.removeAll();
Resource projectNatureRes = model.createResource(resourceURI+":PROJECT_NATURE");
Property projectNatureRiskProps = model.createProperty(resourceURI + ":COMPLEX_FUNCTIONALITY");
Bag projectNatureRisks = model.createBag();
projectNatureRisks.add("More defects");
projectNatureRisks.add("Effort estimation inaccurate");
projectNatureRes.addProperty(projectNatureRiskProps, projectNatureRisks);
Property migrationRiskProps = model.createProperty(resourceURI + ":MIGRATION");
Bag migrationRisks = model.createBag();
migrationRisks.add("Lack of knowledge of exsting application");
migrationRisks.add("Documentation not available");
projectNatureRes.addProperty(migrationRiskProps, migrationRisks);
model.write(System.out);
model.write(new FileOutputStream(new File(directory + "/Project_risk.ttl")), "N-TRIPLES");
model.commit();
dataset.commit();
TDB.sync(model);
} finally {
dataset.end();
model.leaveCriticalSection();
}
}
}
And this is how I read in the data from a java program
public class ReadBasicQn {
public static void main(String[] args) {
String directory = "D:/mywork/dp/projs/static-risks/data/test";
Dataset dataset = TDBFactory.createDataset(directory);
Model model = null;
ResultSet rs;
QueryExecution qexeExecution = null;
try{
/*model = ModelFactory.createDefaultModel();
TDBLoader.loadModel(model, directory + "/Project_risk.ttl");*/
model = dataset.getDefaultModel();
String queryString = "PREFIX proj: <http://www.abc123.com/riskmodelling/static/risks#> ";
queryString += "select ?risks where ";
queryString += "{proj:PROJECT_NATURE proj:COMPLEX_FUNCTIONALITY ?risks}";
String queryString2 = "SELECT * WHERE { ?s ?p ?o }";
Query q = QueryFactory.create(queryString);
qexeExecution = QueryExecutionFactory.create(q, model);
rs = qexeExecution.execSelect();
ResultSetFormatter.out(System.out, rs);
qexeExecution.close();
q = QueryFactory.create(queryString2);
qexeExecution = QueryExecutionFactory.create(q, model);
rs = qexeExecution.execSelect();
ResultSetFormatter.out(System.out, rs);
/*while(rs.hasNext()){
QuerySolution qSol = rs.nextSolution();
RDFNode n = qSol.get("risks");
System.out.println(n);
}*/
}finally{
qexeExecution.close();
}
}
}
The output of the second query (select *) from the ResultSetFormatter shows
------------------------------------------------------------------------------------------------------------------------------------------------
| s | p | o |
===================================================================================================================================================================================================
| <http://www.abc123.com/riskmodelling/static/risks:PROJECT_NATURE> | <http://www.abc123.com/riskmodelling/static/risks:COMPLEX_FUNCTIONALITY> | _:b0 |
| <http://www.abc123.com/riskmodelling/static/risks:PROJECT_NATURE> | <http://www.abc123.com/riskmodelling/static/risks:MIGRATION> | _:b1 |
| _:b0 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> | <http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag> |
| _:b0 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#_1> | "More defects" |
| _:b0 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#_2> | "Effort estimation inaccurate" |
| _:b1 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> | <http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag> |
| _:b1 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#_1> | "Lack of knowledge of exsting application" |
| _:b1 | <http://www.w3.org/1999/02/22-rdf-syntax-ns#_2> | "Documentation not available" |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
which means data is available and correctly loaded (correct ?). The custom query however returns the following output.
---------
| risks |
=========
---------
Any help is appreciated. I have just about started with Jena, so maybe I am doing something really foolish.
There's a typo. Your prefix ends in #, but in your URIs, there's a :. Here's your prefix declaration and URI, lined up:
prefix proj: http://www.abc123.com/riskmodelling/static/risks#>
http://www.abc123.com/riskmodelling/static/risks:PROJECT_NATURE
^
|
In your URI, it's risks[COLON]PROJECT_NATURE, not risks[HASH]PROJECT_NATURE. You need to change your prefix to:
prefix proj: http://www.abc123.com/riskmodelling/static/risks:>
or change your data to
Resource projectNatureRes = model.createResource(resourceURI+"#PROJECT_NATURE");
// ...and in a few other places, too
I had a similar issue, but for me it came from a corrupt TDB Dataset that early on didn't throw an exception but returned results similar to the OP. Another variation of a strange result is a blank row in place of a result that I received. I was forced to rebuild the Dataset from the original source again once I received the Impossible Large Object exception. So if you see weird results, rebuilding the dataset from scratch (clearing previously existing Dataset files from the HDD) might be one way to go, depending on your situation of course.
I have a fairly simple problem. I need to get likeness a tree from the result of the stored procedure. But unfortunately all the examples I've found, used or tables, or uniform structure of the tree.
Stored procedure can return:
| firm_id | index_id | value |
| 1 | 101 | 123 |
| 1 | 102 | 123 |
| 2 | 101 | 123 |
I'm trying to divide by class:
#Entity
#NamedNativeQuery(
name = "getReport",
resultClass = Report.class,
query = "{call myProc(?)}",
callable = true
)
public class Report {
#Id
#Column(name = "firm_id")
private long firmId;
#Embedded
private List<Index> indexList;
// getters and setters
}
Second class:
#Embeddable
public class Index {
#Column(name = "index_id")
private long indexId;
#Column(name = "value")
private int value;
// getters and setters
}
As a result I get a null. I also tried using #ManyToOne/#OneToMany, but received "Table not found". What am I doing wrong?
Thank you for your attention.