Convert ArrayList<ArrayList<String>> to two dimensional Array in java - java

How can I convert this type of Arraylist to Two Dimensional Arraylist ?
ArrayList<ArrayList<String>> two = new ArrayList<ArrayList<String>>();
In android ExpandableListView does not allow to use Arraylist to populate the listview. But I have to dynamically populate the data from JSON web service. How Can I solve this issue ?
Any help would be great !

If you're coming from a JSON object, then the data is already in the format that you want. It's already an array of arrays. You can just loop through the first array assigning the second as you go.
String[][] foo = new String [myJsonObject.getStringArray("arrayOfArrays")).length() ][];
for(int i = 0; myJsonObject.exists("array_" + i); i++){
foo[i] = myJsonObject.getStringArray("array_" + i);
}
I didn't test this, so the syntax might not be 100% but you get the idea.

You just create a Hashmap first and put data to the hashmap. And then Create a Arraylist and put hashmap inside arraylist. That is i done in my case of multidimensional array.

Related

Creating an Array made from ArrayLists

In a given homework problem I'm supposed to create a matrix/or two-dimensional array of 2x9 dimensions in which each element contains an arraylist of objects of "Patient" type.
Patient is an object created from the class Patients.
Is that even possible? How do I even declare such a thing?
I tried:
<ArrayList>Patients[][] myArray = new ArrayList<Patients>[2][9];
but it didn't work. I'm not really sure how to even make an array[][] of ArrayList-objects.
EDIT
With everyone's help I have now initialized the bidimensional-Arraylist as:
ArrayList<Patients>[][] patientsMatrix = new ArrayList[2][9];
But I'm now kind of stuck at how to enter each element, I tried with this format:
patientsMatrix[0][j].add(myPatientsList.get(i));
I'm getting a java.lang.NullPointerException at the first item it reads, I thought that by declaring the matrix with "new ArrayList[2][9]" at the end it wouldn't throw this kind of exception?
myPatientsList is a patient-type arraylist, could it be what is causing trouble here?
ArrayList<Patients>[][] myArray = new ArrayList<Patients>[2][9];
You can also have an ArrayList of ArrayList of ArrayList<Patients>.
Something like ArrayList<ArrayList<ArrayList<Patient>>> patientArray = new ArrayList<>(2)
And then you initialize each of the inner ones like:
for (int i = 0; i < 2; i++) {
patientArray.add(new ArrayList<ArrayList<Patient>>(9));
}
It's essentially a 2-D matrix of dimensions 2x9 of ArrayList<Patients>

Dynamically adding Strings to an object[]

I'm working on a project for work involving a JTable with a dynamic number of columns. Each column is basically a separate transaction but I do not know the number of transactions a file will have ahead of time.
Typically when I create a JTable I know how many columns I will have and I declare it like this:
String header[] = new String[]{
"Tag","Transaction1"
};
For this project however there can be any number of transactions each time the program is used so I would need to dynamically add columns based upon the length of a certain array before I even create my rows. (The first row is actually going to also be used as a header).
So I have an array with a given length, but I don't know how to use this value in a loop, at least not with creating an object like the code above shows.
For example let's say the user uploads a file that has 3 transactions.. I would need my String header[] to read:
String header[] = new String[]{
"Tag","Transaction1","Transaction2","Transaction3"
};
I'd considered possibly creating an array list and adding the transactions to this using a counter and a loop, then possibly extracting the values into the String[] header although I'm not sure if this is the best approach and even still how exactly to make it work.
I actually found the answer to this.. Apparently I need to scrap the entire array and add them like this..
DefaultTableModel tableModel = new DefaultTableModel();
for(String columnName : columnNames){
tableModel.addColumn(columnName);
}
jTable.setModel(tableModel);
A good option for you would be to have an ArrayList to dynamically add or remove elements from the List.
Then, when necessary, you can turn that ArrayList into an array of Strings, like..
ArrayList<String> elements = new ArrayList<String>();
elements.add("Transaction 1");
elements.add("Transaction 2");
elements.add("Transaction 3");
Object[] elementArray = elements.toArray();
I thing you dont need to use an Array, use better an List, this because you can increase the size as much as you need, iterate it, parse it to string-Arrays etc.
Example
List<String> transactions = new ArrayList<String>();
transactions.add("Tag");
// later
transactions.add("Transaction1");
transactions.add("Transaction2");
// print it
for (final String string : transactions) {
System.out.println(string);
}
List<String> headerList = new ArrayList<>();
headerList.add("Tag");
for(int i=1; i <= transactions.length; i++){
headerList.add("Transaction" + i);
}
String[] header = headerList.toArray(new String[headerList.size()]);
I believe what you're looking for is an ArrayList, not an Array nor List, as this allows for dynamic allocation.
The syntax would be:
List<String> header = new ArrayList<String>();
header.add("Tag");
That initializes it. Then, use length() from your File class to set a parameter for a loop, then dynamically add the result of string concatenation with the "Transaction" + your loop index to your ArrayList.
That'd look like:
for (int i = 1; i <= file.length(); i++){
header.Add("Transaction" + i);
}
And, then you can convert it back to an array of strings with:
String[] headerArray = header.toArray(new String[header.size()]);

Inserting a String[] into a String[] in Java?

How do you add a String[] into a String[] in Java? To be more clear, my desired output is:
String[][] out = {{"A", "AA"},{"B", "BB"}};
I don't know the size of the output array, it can contain more then two elements. Basically, I wanted to do it like this (don't mind the syntax it's a blend of Python):
String [] out;
String[] temp = {"A","AA"};
out.append(temp)
So now out should look like {{"A","AA"}}. Then I can append {"B", "BB"} creating the desire output above? This is what my thought was, but I'm not sure if it can be done. I am more experienced with Python and it can be done in Python, but I am wanting to do this in Java. Any ideas?
As in the comment mentioned, you can use the List to store all the array values inside.
It is when you put in:
List<String[]> list = new ArrayList<>();
String[] array = {"A", "B"};
list.add(array);
...
And it is when you get out:
String[] array = list.get(0 /*i*/);
Try using List for this purpose as you would have more operations to perform on Lists than an Array.
List<List<String>> out = new ArrayList<>();
List<String> temp = new ArrayList<String>();
temp.add("A");
temp.add("AA");
out.add(temp);
Read through the Javadocs for more on this.
You can either use List or ArrayList that dynamically grows.
ArrayList al = new ArrayList();
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
For differences between List and ArrayList Type List vs type ArrayList in Java
Detailed Methods of ArrayList
You could try this way too if you exactly want to add dynamic array of Strings into another dynamic array.
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
Because in Java, Array is a fixed length data structure so you should try java List which supports dynamically insertion and deletion of elements. An example using java.util.ArrayList is following:
java.util.List<String[]> out = new java.util.ArrayList<String[]>();
String[] temp = {"A","AA"};
out.add(temp);//insertion
And using index (started from 0), we can get element like out.get(0); and can remove element like out.remove(0);

how to get just one item from array of strings if the other is the same

I want to know if there is a function in Java retrieve one string from array of strings if the other strings are the same i.e. if I have in my array :
yes,yes,yes,yes,no,no,no,no .. I want to get only one yes and one no and display them!
and not by using for loop and comparing ! , just I want to know if this function exists in Java .
Insert all those into a Set.Then u will get like that
String[] array = {"yes","yes","yes","yes","no","no","no","no"};
Set<String> mySet = new HashSet<String>(Arrays.asList(array));
Set does not allow duplicates.
Finally the set contains yes and no(only 2 elements)
If this is your array
String[] a = {"yes","yes","yes","yes","no","no","no","no"};
then this will display unique values
System.out.println(new HashSet(Arrays.asList(a)));
Dump your array into a set and use that:
Set uniqueStrings = new HashSet(Arrays.asList(yourArray));
If you need it as array again you can use
String[] uniqueStringsArray = uniqueStrings.toArray(new String[uniqueStrings.size()]);
Internally, this iterates through the array and compares the Strings. You cannot avoid that.
Try some thing like this
String[] arr=new String[]{"yes","yes","yes","yes","no","no","no","no"};
Object[] unique = new HashSet<>(Arrays.asList(arr)).toArray();
System.out.println(unique[0]);
System.out.println(unique[1]);

Unable to get values from a hashmap which uses a arraylist as value is cleared

I am working on a piece of code which has a Hashmap. This hashmap has a string as key and an arraylist as value. I populate the arraylist and then put the value into the hashmap. After putting the value, I want to clear the arraylist so that no old values are present.
Please see below code:
ArrayList<Bean> elements = new ArrayList<Bean>();
for(int j=0; j<array.length; j++){
String[] id = {"2439","70212","9021","0104","0255","10353","3889","8990","10277"};
String[] Title = {"Gulliver","Good=Guys","Gnomeo","Gene","ABCD","High","Green=Lantern","Gnomeo2","WXYZ"};
for(int i=0; i<id.length; i++){
Bean bean = new bean();
bean.ID(id[i]);
bean.Title(title[i]);
elements.add(bean);
}
udbResults.put(array[j], elements);
elements.clear();
}
Now when i try to print the values from the hashmap, i am not getting any content. This maybe because of the arraylist.clear(). Why does this happen?
Also I didnt want to create new arraylist for each data hence i wanted to remvoe the contents but its not working.
Any way to go about this.
Thanks,
swati
what you r doing is simply createing and populating an arraylist, then you are puting a link to arraylist into hashmap...so now you have 2 links for one arraylist. One was called 'elements' another in hashmap. And then you r deleting all elements from your arraylist. Ofcause you will lose everething. So now you still has two links but to the empty arraylist

Categories

Resources