Convert String [] into ArrayList - java

I want to get location name from mysql database. I want to retrieve all location name and collect in ArrayList and this List requested by setAttribute to jsp.
ArrayList<Bean> SupplyLocation = new ArrayList<Bean>();
try {
//...
while(rs.next()) {
Bean Location = new Bean();
String supply[] = (rs.getString("location_name")).split(",");
for(int i=0; i<supply.length; i++) {
Location.setLocation(supply);
SupplyLocation.add(Location);
}
}
}

you created only one object Location, so it will be modified later in for loop, so you will end up with one object with supply from supply[lastIndex] in that object, and all references in ArrayList will point to it.
Fixed:
while(rs.next()) {
String supply[] = (rs.getString("location_name")).split(",");
for(int i=0; i<supply.length; i++) {
Bean Location = new Bean();
Location.setLocation(supply[i]);
SupplyLocation.add(Location);
}
}
In this way, you create new object Bean for each string in supply array, then you set string supply[i] to it, and you place a reference to it in SupplyLocation.

Considering that your string is comma seperated, then do this,
String supply[] = (rs.getString("location_name")).split(",");
for(int i=0; i<supply.length; i++) {
Location.setLocation(supply);
SupplyLocation.add(Location.toString());
}

Related

Take all classes from .owl file and compare with another classes using Java

I already generated an ont.owl file using Jena. Then first I need to take all the classes to the array list which are contain the ontology. secondly I will give another classes(terms) using my code and check whether these classes contain generated ontology or not. following is the code up to now.
m.read("http://localhost/myontofile/ont.owl");
ExtendedIterator<OntClass> classes = m.listClasses();
while (classes.hasNext()) {
OntClass takeclasses = (OntClass) classes.next();
String ontcls = takeclasses.getLocalName().toString();
ArrayList<String> listiter = new ArrayList<String>();
listiter.add(ontcls);
System.out.println("classes: " + listiter); ----------????
///////////////////////////////////////
ArrayList<String> tempTerms = new ArrayList<String>();
for(int i=0; i < terms.size(); i++) {
String aTerm = terms.get(i) ;
tempTerms.add(aTerm);
}
terms.add("Information");
terms.add("Video Information");
terms.add("Video Price Information");
terms.add("Video Maximum Price Information");
terms.add("Action Video Price Information");
for(int i=0; i < terms.size(); i++) {
if (listiter.equals(terms.get(i))==true) {
System.out.println("ok");
}
else {
System.out.println("no");
}
}
}
Result is always come to else ("no") part. "classes" give out put as only one class. What are the changes I need to do?

Java: Gson change property name without serialization

Is it possible to change the name of a Json property without serialization with Gson? For example, given this Json
{
"1": {
...
},
"2": {
...
}
}
could I change the "1" to a "3" without removing its contents. I know that the addProperty method adds a new property, or overwrites an existing property with a new value, but I want to change the name of a property without affecting its value. Also, pasting the existing value as the second argument of addProperty will not suffice.
EDIT: To add more context, I will explain the bigger picture. I have a JSON string that is a couple thousand lines long. I'm writing a program leveraging Gson in order to change the values in that JSON string. I am at a point where I not only want to change the values of properties, but the names of the properties themselves. I have done everything so far without serialization.
Here is a snippet of the Java I wrote:
String file = "\\temp.json";
FileReader reader = new FileReader(file);
JsonStreamParser parser = new JsonStreamParser(reader);
// Parse entire JSON
JsonElement element = parser.next();
// Get root element
JsonObject sites = element.getAsJsonObject();
// Get first child element
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
for(int i = 1; i < 12; i++) {
// "Dynamic" variable
String num = Integer.toString(i);
// Get property whose name is a number, has siblings
JsonObject one = custCluster1.getAsJsonObject(num);
one.getAsJsonObject().addProperty("name", "cluster" + i);
JsonObject subOne = one.getAsJsonObject("SUB");
subOne.getAsJsonObject().addProperty("name", "aName" + i);
for(int n = 1; n < 1002; n++) {
// "Dynamic" variable
String inst = Integer.toString(n);
// Get property whose name is a number, has siblings
JsonObject subSub = subOne.getAsJsonObject(inst);
// If the property doesn't exist, then don't execute
if(subSub != null) {
JsonArray subSubArray = subSub.getAsJsonArray("SUBSUB");
subSub.getAsJsonObject().remove("name");
int m = 0;
while(m < subSubArray.size()) {
subSubArray.get(m).getAsJsonObject().remove("SR");
subSubArray.get(m).getAsJsonObject().remove("FI");
subSubArray.get(m).getAsJsonObject().remove("IND");
subSubArray.get(m).getAsJsonObject().addProperty("ST", "1");
subSubArray.get(m).getAsJsonObject().addProperty("ID", "2");
subSubArray.get(m).getAsJsonObject().addProperty("DESCR", "hi");
m++;
}
m = 0;
}
}
}
Thanks to #mmcrae for helping and suggesting this method.
Since I'm already saving the (key, value) pairs in variables, you can remove the property whose name you want to change from the parent, and then add it back with a new name and the content that was already saved.
Like this:
JsonObject sites = element.getAsJsonObject();
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
site1.remove("CLUST");
site1.add("NEWCLUST", clust1);

Parse comma separated list java

I have a list
List<List> rows = (List<List>) responseMap.get("data");
[[FRPP, PE103, , USD], [FRPP, PE313AHMR, , USD]
And I want to set the data to the fields of a bean (which represents all the fields for each line)
ArrayList data = new ArrayList();
for (int i = 0; i < 10; i++) {
Bean line = new Bean();
line.setField1("element1");
line.setField2("element2");
line.setField3("element3");
line.setField4("element4");
data.add(line);
}
How can I do that?
Using JDK 1.6, Windows
You are getting list in the format of [[FRPP, PE103, , USD], [FRPP, PE313AHMR, , USD].
Use ArrayList.get(int) to get value of each index value.
for (int i = 0; i < rows.size(); i++) {
Bean line = new Bean();
ArrayList al=(ArrayList)rows.get(i);//now [FRPP, PE103, , USD]
line.setField1((String)al.get(0));//FRPP
line.setField2((String)al.get(1));//PE103
line.setField3((String)al.get(2));//
line.setField4((String)al.get(3));//USD
data.add(line);
}

String cannot be added to List using Object in Java

I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.

How to convert String to ArrayList

I need your help about retreive data from mysql db. I cant add string to array list.
my list declare
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
here my code
report_data = json.getJSONArray(TAG_REPORT_DATA);
for (int i = 0; i < report_data.length(); i++) {
//storing variable
JSONObject c = report_data.getJSONObject(i);
String reportID = c.getString(TAG_REPORT_ID);
String userID = c.getString(TAG_UID);
String projectName = c.getString(TAG_PROJECT_NAME);
String localWork = c.getString(TAG_LOCATION);
String timeStart = c.getString(TAG_TIME_START);
String timeEnd = c.getString(TAG_TIME_END);
Log.d(TAG_LOCATION, localWork);
// add data to Arraylist
reportList.add(new HandleListReport(reportID, userID, projectName, localWork, timeStart, timeEnd));
my problem my listReport missing string data. Logcat show reportList ---> []
thanks for answer!
create a list of string
List<String> list ......
list.add(String)
then list.toArray() method
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray(T[])
it seems you are trying to store object of HandleListReport in arraylist. In that case use the following to initiate
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
It seems that the length of variable report_data is 0, so the element does not add the list.

Categories