How to set Data to multidimensional array in Java? - java

I try to set data from list to two multidimensional array.
Normally I can set data to two multidimensional array like this:
Object[][] newData = {
{ "test", "test2", 15.98, 0.14, "+0.88%",
32157250 },
{ "AAPL", "Apple Inc.", 126.57, -1.97, "-1.54%", 31367143 }"
However I want to set data dynamically from list .
I have a method wich return a list :
List<User> user = listUser(id);
static User {
private int id;
private String name;
and getter(...),setter(..).
I need to set user from listUser(id) method to Object[][] array.
I try to do it but I couldnt get succesfull result :
for (int i=0;i<user.size();i++){
for(int j=0;j<user.size();j++){
newData[i][j]=user.get(i).getName();
}
}
Could you help me ?

The columns are fixed, i.e., 0,1,2,etc.. and you need to iterate and set the data for each row as shown below:
for (int i=0;i<user.size();i++){
for(int j=0;j<user.size();j++){
newData[i][j]=user.get(i).getId();//get id for each rowand set to 0th column
newData[i][j]=user.get(i).getName();
newData[i][j]=user.get(i).getX();//other fields
newData[i][j]=user.get(i).getY();//other fields
}
}
Also, it is not a good idea to use Object[][] (not sure for what reason you are using this) as it requires explicit casting while retrieving/using the fields.

It looks like the data is well structured. I would create a class and keep a single-dimension array of your private "CompanyStock" class instead of using a dangerous 2d Object[][] array.

Related

how to store, retrieve and change values using java

I want to save item number, CO number, CO line, qty inside an array then I'm saving that array inside array list. For some records inside array list I want to retrieve that record based on CO number and CO line and change the qty of it.
What is the easiest way to do this? Maybe storing inside array and storing those arrays inside Array list in not a good idea. I'm doing this development inside an integration system. Therefore there is limitations like can only use single Java class file etc.
This is what I have tried so far.
//Loop arraylist
for (int i = 0; i < g_COList.size(); i++) {
//Get array
String[] CO = (String[]) g_COList.get(i);
coNumber = CO[0];
coLine = CO[1];
if (coNumber.equals("567780000") && coLine .equals("10")) {
g_COList.set(i, new String[] { "45", "567780000", "10", "5"});
}
}
Thank you
The best way to do this is using a class , creating a class CO that will store your attributes { item number , CO number , CO line ... etc }
Then each time you wanna add an element to your arraylist it will be an object containing your informations , like this :
ArrayList<CO> list = new ArrayList<CO>();
CO object = new CO(.....); // filled with your informations
list.add(object);
To extract COnumber and COline :
for ( CO object : list ) {
System.out.println( object.getCOnumber() ); // use getters to extract
System.out.println( object.getCOline() );
object.setQty( ... ); // use setters to modify ( ... : you new qty )
// so here the idea of retreiving objet with certain COnumber or COline
//seems easy
if ( object.getCOnumber() == " .. " && object.getCOline() == " .." ) {
object.setQty( ... );
}
}
You can store plain array within your ArrayList, that's absolutely fine and you can use C style for loop for the sake of performance as this code would be faster in comparison to storing data in objects inside the list and then traversing the array list. If you're not operating on large data set the I would recommend you to leverage Object Oriented programming in your code. Following would be the code that you can write. \n
Your Item class
#lombok.Getter
#lombok.Setter
#lombok.Builder
public class Items {
private long itemNumber;
private long coNumber;
private long coLine;
private long quantity;
}
This is how you would traverse the List of Items
I am assuming that getData() method would give you list of items and then will work on it. I am creating another List of items with your new values in it.
ArrayList<Items> list = getData();
List<Items> newList = list.stream()
.filter(items -> items.coNumber == 567780000L && items.coLine == 10L)
.map( items -> Items.builder()
.itemNumber(items.itemNumber)
.coNumber(items.coNumber)
.coLine(items.coLine)
.quantity(45L) //new quantity
.build())
.collect(Collectors.toList());
You can also made changes to the source stream but it's not advisable, you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that: Non Interference doc
Anyway, code is as below
list.stream()
.filter(items -> items.coNumber == 567780000L && items.coLine == 10L)
.forEach(items -> items.setQuantity(45L));

JTable with data from properties file

I have simple JTable object with 2 columns. I want to put here values from file.properties but I don't know how do this.
For example file.properties looks like:
some1.text1=Text1
some1.text2=Text2
some2.text1=Text_1
some2.text2=Text_2
And now I want to add these data to TableModel like this(it's example from swing):
Object rowData[][] = { { some1.text1, some2.text1 }, ... };
How can I do this?
You would NOT create a 2 dimensional array since you may not know how many properties you have.
Instead you would create one row of data for each property and then add the row to the DefaultTableModel. The basic logic would be something like:
String columnNames = { "Column1", "Column2" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (each property pair)
{
Vector<String> row = new Vector<String>(2);
row.addElement( get first value );
row.addElement( get second value );
model.addRow( row );
}
JTable table = new JTable( model );
I found one way to do this using 'new Property()'
This read my file.propertieswell but now I'm interesting something else. How can I read my file in other way, for example my file.property looks like:
some.1.name=...
some.1.value=...
some.2.name=...
some.2.value=...
I can read each of them like this
#ResourceBundleBean(key="some.1.name")
private String some_1_name;
#ResourceBundleBean(key="some.1.value")
private String some_1_value;
etc...
But if is there possibility to use only one String field for for name and value(Value is String too) OR only 1 String field to get each property some.1. some.2. etc and get from this field name and value?
For example if my file.properties will have many item only with name/value some like:
some.1.name=...
some.1.value=...
...
some.200.name=...
some.200.value=...
I do not want to create 200 fields to do this. Is it possible?
Or if it is not possible how can I read arrays from property?
Instead of upper properties make some like this:
some.[1].name=n1
some.[1].value=v1
...
some.[200].name=n200
some.[200].value=v200
And how can I read this array to use it for output some like:
n1 - v1
...
n200 - v200

Change value of multidimensional ArrayList

I need a solution to change the value of an element in a multidimensional ArrayList in Java. This is my ArrayList:
public class Users {
ArrayList<ValidateUser> personer = new ArrayList<ValidateUser>();
public Users() {
personer.add(new ValidateUser("admin", "asdf123", 0.8, "admin"));
personer.add(new ValidateUser("jesper", "ukamm19", 2.5, "user"));
personer.add(new ValidateUser("lars", "lol123", 1.5, "user"));
}
I want to change the double value (0.8) at the user "admin", for example.
This would be done from another a class.
How to do so?
Thanks in advance! :)
As I've stated in my comment, just iterate through the list to find the object. If you're going to do this a lot, consider using a map.
for (ValidateUser user : personer)
if (user.getName().equals("admin"))
user.setNumber(someNumber);
First, note that this is not a multidimensional array, is just a list that holds elements of ValidateUser class object references. Second, you need to access to the element before updating it. You have several ways to accomplish this:
Implement the equals and hashCode methods in your ValidateUser class, then just retrieve the object from your List:
ValidateUser adminUser = personer.get(new ValidateUser("admin", "", 0.8, ""));
adminUser.set...
Note: this looks ridiculous but will work (assuming your equals method only checks by the field that holds this "admin" value.
Navigate through the array and seek for the desired element manually, then update it:
for (ValidateUser user : personer) {
if ("admin".equals(user.getXxx()) {
user.set...
break; //don't forget this!
}
}
Use a different data structure like a Map<String, ValidateUser> to store your data and faster retrieval:
Map<String, ValidateUser> personerMap = new LinkedHashMap<String, ValidateUser>();
personerMap.add("admin", new ValidateUser("admin", ...);
//fill the map with other values...
//if you still want a Collection<ValidateUser> personer variable
Collection<ValidateUser> personer = personerMap.values();
//now check for the desired element
ValidateUser admin = personerMap.get("admin");
if (admin != null) {
admin.set...
}
By comments, your ValidateUser is an immutable object, so you cannot update its fields using setters (because there aren't). So, the best approach here is to use a ListIterator<ValidateUser> instead (not to confuse with Iterator) and replace the element by your modified object. Here's an example:
//the new immutable ValidateUser that will replace the older one...
//set the parameters as needed
ValidateUser newAdmin = new ValidateUser("admin", ...);
ListIterator<ValidateUser> listIterator = personer.listIterator();
while (listIterator.hasNext()) {
ValidateUser validateUser = listIterator.next();
if ("admin".equals(validateUser.getXxx()) {
listIterator.set(newAdmin);
break;
}
}

How to compare list of records against database in Java?

How to compare list of records against database? I have more than 1000 records in list and need to validate against database. How to validate each record from list to database? Select all the data from database and stored in list, then have to compare the values? Please advise...
The below code lists values to validate against database.
private void validatepart(HttpServletRequest req, Vector<String> errors) {
Parts Bean = (Parts)req.getAttribute("partslist");
Vector<PartInfo> List = Bean.getPartList();
int sz = partList.size();
for (int i = 0; i < sz; i++) {
PartInfo part = (PartInfo)partList.elementAt(i);
System.out.println(part.getNumber());
System.out.println(part.getName());
}
}
This depends on what you mean by compare. If it's just one field then executing a query such as select * from parts_table where part_number = ?. It's not that much of a stretch to add more fields to that query. If nothing is returned you know it doesn't exist.
If you need to compare and know exactly which values are different then you can try something like this
List<String> compareObjects(PartInfo filePart, PartInfo dbPart) {
List<String> different = new LinkedList<String>();
if (!filePart.getNumber().equals(dbPart.getNumber())) {
different.add("number");
}
//repeat for all your fields
return different;
}
If your list of objects that you need to validate against the database includes a primary key, then you could just build a list of those primary key values and run a query like:
SELECT <PRIMARY KEY FIELD> FROM <TABLE> WHERE <PRIMARY_KEY_FIELD> IN <LIST OF PRIMARY KEYS> SORT BY <PRIMARY KEY FIELD> ASC;
Once you get that list back, you can compare the results. My instinct would be to put your data (and the query results too) into a Set object and then call removesAll() to get the items not in the database (reverse this for items in the database but not in your set):
yourDataSet.removeAll(queryResults);
This assumes that you have an equals() method implemented in your PartInfo object. You can see the Java API documentation for more details.

Android: Handling json objects that can be a string or array

Ran into a situation where am not sure how to handle it.
I have json data that comes from a server; for example:(am just posting part of the json, so, yes, the json is valid)
"wall_id": 889149,
"poster_image_thumbnail": "http:\/\/www.mface.me\/images\/avatar\/thumb_62441559ddb1dda7513d0f94.jpg",
"post_type": "profile",
"post_content": [{
"text": "",
"images_count": 1,
"images": ["https:\/\/fbcdn-sphotos-a-a.akamaihd.net\/hphotos-ak-ash4\/227408_475848819113499_663318592_n.jpg"]
}]
Created a class to store this json data
public class feedFormat{
Integer wall_id;
String poster_image_thumbnail;
String post_type;
String post_content;
}
There are times when post_content can be empty or an array as the example above. I have declared post_content as String in feedFormat. This is obviously throwing a cast exception (Converting array to string?).
I was expecting JSONObject to read it as a string and later convert it into an array from there, but does'nt seem to go that way.
How can i dynamically handle a string or an array? if it is an array, i need to break it down.
I am porting this app from IOS to android, there is a "id" object in IOS that can be of any class. I check if the class is a NSSTring or NSArray and take it from there. Here in Java, am not sure how to handle it.
Any suggestions are highly appreciated
If your JSON array is empty, it will be like that :
"post_content": []
It will then remain an array, with the particularity of being 0-sized.
Then I suggest you parse directly your JSON array into a appropriate data structure, whatever the size, like an ArrayList> for example. You will then be able to go through all the items of your JSON array, and for each item, add a new HashMap in your arraylist. Every hashmap will contain there pairs of key values.
However, if I understand well your JSON, it seems that it will be always an array of three elements, the third element being itself a array, which size is given bu the attribute images_count. This is not very good, your JSON structure should be :
"post_content": {
"text": "",
"images": [
"https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/227408_475848819113499_663318592_n.jpg"
]
}
Since images is an array, you can easily get its size.
JSONObject has functions called has(String key) which checks if there is a mapping for a key and isNull(String key) which checks if a particular key is null. Use these to check the key before reading.
public class FeedFormat{
Integer wall_id;
String poster_image_thumbnail;
String post_type;
JSONArray post_content;
}
feedFormat toto = new feedFormat();
toto.post_content = yourJsonObject.getJsonArray("post_content");
This is the easiest way to do what you want. Another way is to create another class.
public class FeedFormat{
Integer wall_id;
String poster_image_thumbnail;
String post_type;
ArrayList<PostContent> post_content = new ArrayList<PostContent>();
}
public class PostContent {
String text;
Integer imageCount;
ArrayList<String> images = new ArrayList<String>();
}
With that you can handle each post content into specific object instead of use JSONObject / JSONArray.
you can check like this jsonobject.has("post_content")
if(jsonobject.has("post_content")) {
/// read array and do remaining stuff
}else {
// if not read another strings and put post_content as null.
}
You can use something like this:
String data= "wall_id": 889149,
"poster_image_thumbnail": "http:\/\/www.mface.me\/images\/avatar\/thumb_62441559ddb1dda7513d0f94.jpg",
"post_type": "profile",
"post_content": [{
"text": "",
"images_count": 1,
"images": ["https:\/\/fbcdn-sphotos-a-a.akamaihd.net\/hphotos-ak-ash4\/227408_475848819113499_663318592_n.jpg"]
}]
JSONArray jArray=data.getJSONArray("post_content");
for(int i=0; i<jArray.length(); i++)
{
JSONObject jObj=jArray.getJSONObject(i);
String text=jObj.getString("text");
int images_count=jObj.getInt("images_count");
String images=jObj.getInt("images");
}

Categories

Resources