Converting List<ArrayList> to String[] - java

I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6

It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}

String headers = "";
for (String header:arg)
{headers += header;}

Related

Extract String arrays from List

Developing a Java Android App but this is a straight up Java question i think.
I have List declared as follows;
List list= new ArrayList<String[]>();
I want to extract each String [] in a loop;
for(int i=0; i < list.size(); i++) {
//get each String[]
String[] teamDetails = (String[])list.get(i);
}
This errors, I am guessing it just doesn't like me casting the String[] like this.
Can anyone suggest a way to extract the String[] from my List?
Use a List<String[]> and you can use the more up-to-date looping construct:
List<String[]> list = new ArrayList<String[]>();
//I want to extract each String[] in a loop;
for ( String[] teamDetails : list) {
}
// To extract a specific one.
String[] third = list.get(2);
Try declaring the list this way
List<String[]> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
//get each String[]
String[] teamDetails = list.get(i);
}
Moreover the call of your size function was wrong you need to add the brackets
/*ArrayList to Array Conversion */
String array[] = new String[arrlist.size()];
for(int j =0;j<arrlist.size();j++){
array[j] = arrlist.get(j);
}
//OR
/*ArrayList to Array Conversion */
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
In for loop change list.size to list.size()
And it works fine Check this https://ideone.com/jyVd0x
First of all you need to change declaration from
List list= new ArrayList<String[]>(); to
List<String[]> list = new ArrayList();
After that you can do something like
String[] temp = new String[list.size];
for(int i=0;i<list.size();i++)`
{
temp[i] = list.get(i);
}

populating a java array with a variable

I am trying to populate a java string array with a variable. the variable contains values which I am reading in from a text file. every time a new value is stored in the array the current value is replaced by the new value.
the code below is what i have tried so far.
int n = 0;
String var1 = value;
String array[] = {var1};
String [] array = new String[n];
for (int i =0; i < n; i++) {
array[n++] = value;
}
Java has only fixed sized arrays; dynamically growing "arrays" are realized with List:
List<String> array = new ArrayList<>();
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array.add(s);
}
for (String t : array) {
System.out.println(t);
}
String seven = array.get(7);
int n = array.size();
if (array.isEmpty()) { ... }
// In Java 8:
array.stream().sorted().forEach(System.out::println);
Using (fixed sized) arrays would be cumbersome:
String[] array = new String[];
String[] otherVar = array;
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array = Arrays.copyOf(array, i + 1);
array[i] = s;
}
Here on every step a new array is created, the content of the old array copied.
Also notice that otherVar keeps the initial empty array.
Note that String[] a is the same as String a[]. The latter is only for compatibility to C/C++, and is less readable.
This will add a string indefinitely. When you read all the data from file you have to set isFileNotEnded = false
boolean isFileNotEnded = true;
List<String> array = new ArrayList<>;
while (isFileNotEnded) {
array.add("hello");
//stop here the infinite loop
}

How can I convert List<List<String>> into String[][]?

In my project I have a List that contains Lists of Strings (List<List<String>>) and now I have to convert this List into an array of String arrays (String[][]).
If I had a single List<String> (for example myList) then I could do this to convert to String[]:
String[] myArray = new String[myList.size()];
myArray = myList.toArray(myArray);
But in this case I have lots of List of String inside a List (of List of Strings).
How can I do this? I've spent lots of time but I didn't find a solution..
I wrote a generic utility method few days back for my own usage, which converts a List<List<T>> to T[][]. Here's the method. You can use it for your purpose:
public static <T> T[][] multiListToArray(final List<List<T>> listOfList,
final Class<T> classz) {
final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);
for (int i = 0; i < listOfList.size(); i++) {
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
}
return array;
}
There I've created the array using Array#newInstance() method, since you cannot create an array of type parameter T directly.
Since we're creating a 2-D array, and we don't yet know how many columns you will be having, I've given the column size as 0 initially. Anyways, the code is initializing each row with a new array inside the for loop. So, you don't need to worry about that.
This line:
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
uses the List#toArray(T[]) method to convert the inner list to an array, as you already did. I'm just passing an array as a parameter to the method so that the return value which I get is T[], which I can directly assign to the current row - array[i].
Now you can use this method as:
String[][] arr = multiListToArray(yourList, String.class);
Thanks to #arshaji, you can modify the generic method to pass the uninitialized array as 2nd parameter, instead of Class<T>:
public static <T> void multiListToArray(final List<List<T>> listOfList,
final T[][] arr) {
for (int i = 0; i < listOfList.size(); ++i) {
arr[i] = listOfList.get(i).toArray(arr[i]);
}
}
But then, you have to pass the array to this method like this:
List<List<String>> list = new ArrayList<>();
// Initialize list
String[][] arr = new String[list.size()][0];
multiListToArray(list, arr);
Note that, since now we are passing the array as argument, you no longer need to return it from your method. The modification done in the array will be reflected to the array in the calling code.
String[][] myArray = new String[myList.size()][];
for (int i = 0; i < myList.size(); i++) {
List<String> row = myList.get(i);
myArray[i] = row.toArray(new String[row.size()]);
}
Here is one way
List<List<String>> list = new ArrayList<List<String>>();
String[][] array = new String[list.size()][];
int counter1 = 0;
for(List<String> outterList : list)
{
array[counter1] = new String[outterList.size()];
int counter2 = 0;
for(String s : outterList)
{
array[counter1][counter2] = s;
counter2++;
}
counter1++;
}
To init String[][], you should init the list(array) of String[]
So you need to define a list
List<String[]> string = new List<String[]>();
for (int i = 0;....)
{
String[] _str = new String[numbers];
_str[0] = ...
string.append(_str);
}

How can I transform a List of List (multidimensional List) to an Array of Array(multidimensional Array)?

I have written this code, but at run time I have this error:
[Ljava.lang.Object; cannot be cast to [[Ljava.lang.String;
please help me, thanks!!!
public java.util.List<String> concatAll(java.util.List<java.util.List<String>> mergedList) {
java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
Iterator<java.util.List<String>> itr = mergedList.iterator();
java.util.List<String> list1 = itr.next();
java.lang.String [] firstArray = (String[])list1.toArray();
int totalLength = firstArray.length;
for (String[] array : mergedArray) {
totalLength += array.length;
}
String[] result = Arrays.copyOf(firstArray, totalLength);
int offset = firstArray.length;
for (String[] array : mergedArray) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
java.util.List<String> finalList = Arrays.asList(result);
for (String list : finalList)
System.out.println(list);
return finalList;
}
mergedList.toArray() creates a singly indexed array typed as objects.
Each of the objects it contains is in fact a (singly-indexed) list of strings, though with this call syntax the type is not known at compile-time. It is not an array of strings, as would be needed for your cast to work.
Since your concatAll is trying to convert a List<List<String>> into a List<String> by some sort of concatenation operation, it may be best to do this without ever converting to a String[][] at all, but if you do want that conversion, it can be done as follows:
private String[][] toDoubleIndexArray(List<List<String>> mergedList) {
String[][] result = new String[mergedList.size()][];
for (int i = 0; i< mergedList.size(); i++) {
List<String> currentList = mergedList.get(i);
result[i] = currentList.toArray(new String[currentList.size()]);
}
return result;
}
Original answer, not quite correct as noted by Xavi Lopez in comments:
Since mergedList has type List<List<String>>,
mergedList.toArray() has type List<String>[], i.e., it's an array of lists, and not a doubly indexed array.
There's no out-of-the-box method, but it's fairly straightforward to do by hand:
// Create the outer dimension of the array, with the same size as the total list
String[][] mergedArray = new String[mergedList.size()][];
// Now iterate over each nested list and convert them into the String[]
// instances that form the inner dimension
for (int i = 0; i < mergedList.size(); i++) {
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
A slightly more efficient version of the loop body would be
List<String> innerList = mergedList.get(i);
String[] innerAsArray = innerList.toArray(new String[innerList.size()]);
mergedArray[i] = innerAsArray;
as this avoids the array resizing that would be required in my initial example (the new String[0] isn't large enough to hold the list elements). But quite frankly, unless this was a performance critical loop, I'd prefer the first version as I find it slightly clearer to see what's going on.
Hey you cannot convert the Multi dimentional String list to String array directly. Add the below code before trying to use the mergedArray:
/** Create Array **/
String [][] mergedArray = new String[mergedList.size()][];
/** Initialize array from list **/
for(int i=0; i< mergedList.size(); i++){
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
This should do the trick
I think your return type is wrong if your intention is to return an array of array.
Try this:
public String[][] concatAll(java.util.List<java.util.List<String>> mergedList) {
//java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
java.lang.String[][] mergedArray = new String[mergedList.size()][];
Iterator<java.util.List<String>> itr = mergedList.iterator();
int count = 0;
while (itr.hasNext())
{
java.util.List<String> list1 = itr.next();
String[] array1 = list1.toArray(new String[list1.size()]);
mergedArray[count++] = array1;
}
return mergedArray;
}
You can't convert a
List<List<String>>
to a String[][] by using the out of the box toArray functionality. This would only work if you had:
List<String[]>.

Remove Null array values

I am building an array based off comparing two other arrays. But when I initalize my third array I have to set the length. But that is making my array have null objects in some instances. Is there away I can drop the empty/null postions in the array. See my code so far below:
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public String[] selected_tags = new String[tags.length];
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags[i] = tags[i];
}
}
I left out the code for the checkboxes that builds the Boolen selected [].
Either way if I only select 2 tags then my selected_tags[] array will be Mike, Bob, Null, Null
I need to get the Null Null out. Thanks in advance!
You can use ArrayList, instead of array.
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public List<String> selected_tags = new ArrayList<String>();
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
No, you can't drop the null values (and change the length of the array) after you've created it. You'll have to create a new one (or for instance use an ArrayList as illustrated below):
List<String> list = new ArrayList<String>();
for (int i = 0; i < tags.length; i++)
if (selected[i] == true)
list.add(tags[i]);
// Convert it to an array if needed:
selected_tags = list.toArray(new String[list.size()]);
As others have mentioned, this is much easier with an ArrayList. You can even get a regular array from it with the toArray function.
Without using ArrayList, you would have to figure out the length first and not include the null values. As you can see, that's a little messy:
int length = 0;
for( boolean b : selected ) if(b) ++length; // Count the "true"s
String[] selected_tags = new String[length];
for( int i = 0, j = 0; i < tags.length; i++ )
if( selected[i] )
selected_tags[j++] = tags[i];
Instead of using a standard Java array, you should use an ArrayList : it'll allow you to add elements to it, automatically growing the list as needed.
Basically, you'd first declare / instanciate the ArrayList, without specifying any kind of size :
public ArrayList<String> selected_tags = new ArrayList<String>();
And, then, in your loop, you'd use the add() method to add items to that ArrayList :
selected_tags.add(tags[i]);

Categories