java- how to convert a ArrayList<ArrayList<String>> into String[]][] - java

I want to store some data in an ArrayList<ArrayList<String>> variable into a csv file.
For this purpose, I zeroed in on Ostermiller Utilities- which include a CSV Writer as well.
The problem is, the csvwrite functionality requires a String, String[] or a String[][] variable.
I wont know beforehand the number of rows/columns in my ArrayList of arraylists-- so how do I use the above (cswrite) functionality? Dont I have to declare a fixed size for a String[]][] variable?

A String[][] is nothing more than an array of arrays. For example, this makes a 'triangular matrix' using a 2d array. It doesn't have to be a square (although CSV probably should be square, it doesn't have to be).
String[][] matrix = new String[][5];
matrix[0] = new String[1];
matrix[1] = new String[2];
matrix[2] = new String[3];
matrix[3] = new String[4];
matrix[4] = new String[5];
So for your purposes
String[][] toMatrix(ArrayList<ArrayList<String>> listOFLists) {
String[][] matrix = new String[][listOfLists.size()];
for(int i = 0; i < matrix.length; i++) {
matrix[i]= listOfLists.get(i).toArray();
}
return matrix;
}
Just keep in mind that in this case, it's in matrix[col][row], not matrix[row][col]. You may need to transpose this result, depending on the needs of your library.

Tested and working:
String[][] arrayOfArraysOfString = new String[arrayListOfArrayListsOfStrings.size()][];
for (int index = 0; index < arrayListOfArrayListsOfStrings.size(); index++) {
ArrayList<String> arrayListOfString = arrayListOfArrayListsOfStrings.get(index);
if (arrayListOfString != null) {
arrayOfArraysOfString[index] = arrayListOfString.toArray(new String[arrayListOfString.size()]);
}
}

Here is an Example of how to convert your multidimesional ArrayList into a multidimensional String Array.
package stuff;
import java.util.ArrayList;
public class ArrayTest {
public static void main(String[] args) throws Exception {
ArrayList<ArrayList<String>> multidimesionalArrayList = createArrayListContent();
String[][] multidimensionalStringArray = new String[multidimesionalArrayList.size()][];
int index = 0;
for (ArrayList<String> strings : multidimesionalArrayList) {
multidimensionalStringArray[index] = strings.toArray(new String[]{});
index++;
}
System.out.println(multidimensionalStringArray);
}
private static ArrayList<ArrayList<String>> createArrayListContent() throws Exception {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
return result;
}
private static ArrayList<String> createArrayList() throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
return list;
}
}

You can create an array of arrays (matrix) with one size at first, and then iterate and add the data as you traverse the list of list
String[][] arr = new String[listOfList.size()][];
int i = 0;
for (List<String> row: listOfList) {
arr[i++] = row.toArray(new String[row.size()]);
}

Related

Convert ArrayList<ArrayList<Integer>> to List<List<Integer>>

I have my Integer data in Array Lists of Arrays Lists and I want to convert that data to Lists of List format.
How can I do it?
public List<List<Integer>> subsetsWithDup(int[] nums) {
ArrayList<ArrayList<Integer>> ansList = new ArrayList<ArrayList<Integer>>();
String arrStr = nums.toString();
ArrayList<Integer> tempList = null;
for(int i = 0 ; i < arrStr.length()-1 ; i++){
for(int j = i+1 ; j<arrStr.length() ; j++){
tempList = new ArrayList<Integer>();
tempList.add(Integer.parseInt(arrStr.substring(i,j)));
}
if(!ansList.contains(tempList)){
ansList.add(tempList);
}
}
return ansList;
}
It would be best to share the code where you have this issue. However, you should declare the variables as List<List<Integer>>, and then instantiate using an ArrayList.
For example:
public static void main (String[] args) throws java.lang.Exception
{
List<List<Integer>> myValues = getValues();
System.out.println(myValues);
}
public static List<List<Integer>> getValues() {
List<List<Integer>> lst = new ArrayList<>();
List<Integer> vals = new ArrayList<>();
vals.add(1);
vals.add(2);
lst.add(vals);
vals = new ArrayList<>();
vals.add(5);
vals.add(6);
lst.add(vals);
return lst;
}
In general, program to an interface (such as List).
Based upon the edit to the OP's question, one can see that, as originally suggested, one can change:
ArrayList<ArrayList<Integer>> ansList = new ArrayList<ArrayList<Integer>>();
to
List<List<Integer>> ansList = new ArrayList<>();
And
ArrayList<Integer> tempList = null;
to
List<Integer> tempList = null;
And the code will then conform to the method's return signature of List<List<Integer>>.

Remove row from multidimensional array

I have this multidimensional array:
String[][] qArray = new String[][] {
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"}
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"}
}
I assign the question text to a TextView and the andswerOptions to text on Buttons. The order is randomly selected, so because the question isnt supposed to be asked twice, i need to remove the question just asked. What i have read i need to delete this array and create a new one, but i'm not quite sure how this is done. I'm not sure how the for syntax is in Java, but here is my guess:
Assuming the question asked is held in TextView tv
String[][] newArray = new String[qArray.length-1][5] {
For rows in qArray do newArray.addRow
if (qArray[0..qArray.length][0] != tv.getText());
qArray = newArray
And then redoing the methods again untill there are no more questions left.
If you are just looking for a for loop implementation. why not use something like this
String[][] newArray = new String[qArray.length][5];
for(int i=0; i<=qArray.length-1; i++){
for(int j=0; j<5; j++){
newArray[i][j] = qArray[i][j];
}
}
public static void main(String[] args){
String[][] qArray = new String[][]{
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"},
{"question5", "answerOption6", "answerOption7", "answerOption8", "answerOption9"}
};
List<String[]> list = new ArrayList<String[]>(Arrays.asList(qArray));
list.remove(1);//row that needs to be deteted
String[][] qArray1 = list.toArray(new String[][]{});
for (String[] arr : qArray1) {
System.out.println(Arrays.toString(arr));
}
}
A queue is meant for this.
public static void main(String[] args)
{
String[][] qArray = new String[][]
{
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"},
{"question5", "answerOption6", "answerOption7", "answerOption8", "answerOption9"}
};
Queue<String[]> list = new LinkedList<String[]>(Arrays.asList(qArray));
for (String[] theArr = list.poll() ; theArr!=null ; theArr = list.poll())
{
for (String theStr : theArr)
{
System.out.print(theStr + " ");
}
System.out.print("\n");
}
}

Dynamically creating ArrayList inside a loop

How do we create arraylist dynamically inside a loop?
something like -
for(i=0;i<4;i++)
{
List<Integer> arr(i) = new ArrayList<>();
}
It sounds like what you actually want is a list of lists:
List<List<Integer>> lists = new ArrayList<List<Integer>>();
for (int i = 0; i < 4; i++) {
List<Integer> list = new ArrayList<>();
lists.add(list);
// Use the list further...
}
// Now you can use lists.get(0) etc to get at each list
EDIT: Array example removed, as of course arrays of generic types are broken in Java :(
Creating a list of Arraylist:
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int i=0;
Scanner obj=new Scanner(System.in);
List<List<Integer>> lists = new ArrayList<List<Integer>>();
System.out.println("Enter the number of lists");
int n=obj.nextInt();
while (i<n) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Enter the number of integers you want to enter in an ArrayList");
int d=obj.nextInt();
for(int j=0;j<d;j++){
list.add(obj.nextInt());
}
lists.add(list);
System.out.println("List "+i+ "is created");
System.out.println(lists.get(i));
System.out.println("");
i++;
} //end of while
} //end of main
} //end of class
Maybe you want something like this. This will be creating a number of "List" as much as you want. In this case, I am creating two Lists:
import java.util.LinkedList;
import java.util.List;
public class NumberOfList {
public static void main (String [] args){
List<Integer> list[];
list = new LinkedList[2];
for(int x=0; x<2; x++){
list[x]= new LinkedList();
}
}
}
You can try this.
List<List<Integer>> dataList = new ArrayList<List<Integer>>();
for(int i = 1; i <= 4; i++)
{
List<Integer> tempList = new ArrayList<Integer>();
dataList.add(tempList);
}
For adding data
for(int i = 1; i <= 4; i++)
{
int value = 5+i;
dataList.get(i - 1).add(value);
}
Create an ArrayList having an ArrayList as it's elements.
ArrayList<ArrayList<Integer>> mainArrayList =
new ArrayList<ArrayList<Integer>>();
you can add elements into mainArrayList by:
ArrayList<Integer> subArrayList;
for(int i=0;i<4;i++) {
subArrayList = new ArrayList<Integer>();
subArrayList.add(1); // I'm adding a random value to subArrayList
mainArrayList.add(subArrayList);
}
Now, the mainArrayList will have the 4 arrayLists that we added and we can access
each element(which are ArrayLists) using for loop.
List<List<Integer>> dataList = new ArrayList<List<Integer>>();
for(i=0;i<4;i++)
{
List<Integer> arr = new ArrayList<>();
dataList .add(arr );
}
This might help you. If not, please clarify the scenario.
I am not sure what you mean, maybe this?
List<Integer> arr = new ArrayList<Integer>();
for(i=0;i<4;i++)
{
arr.add(i);
}

Convert List<List<String>> to String[]

I have a requirement wherein i should write a method of type String[] and return the same.But the implementation that i have, uses and returns List<List<String>>.Also the List<List<String>> gets and returns values from the database and the values are not known prior to add them to the String[] directly.The list can also be of a huge size to accomodate it in an String[] . How to get this conversion done.
This should work just fine. Though if you can return your embedded list structure that would be even better:
final List<String> resultList = new ArrayList<String>(64000);
final List<List<String>> mainList = yourFuncWhichReturnsEmbeddedLists();
for(final List<String> subList: mainList) {
resultList.addAll(subList);
}
final String[] resultArr = subList.toArray(new String[0]);
Take a look at this code:
public static String[] myMethod(ArrayList<ArrayList<String>> list)
{
int dim1 = list.size();
int total=0;
for(int i=0; i< dim1; i++)
total += list.get(i).size();
String[] result = new String[total];
int index = 0;
for(int i=0; i<dim1; i++)
{
int dim2 = list.get(i).size();
for(int j=0; j<dim2; j++)
{
result[index] = list.get(i).get(j);
index++;
}
}
return result;
}
Run this test code:
public static void main(String[] args)
{
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
list1.add("first of first");
list1.add("second of first");
list1.add("third of first");
list2.add("first of second");
list3.add("first of third");
list3.add("second of third");
ArrayList<ArrayList<String>> superList = new ArrayList<ArrayList<String>>();
superList.add(list1);
superList.add(list2);
superList.add(list3);
String[] output = myMethod(superList);
for(int i=0; i<output.length; i++)
System.out.println(output[i]);
}

Convert array list items to integer

I have an arraylist, say arr. Now this arraylist stores numbers as strings. now i want to convert this arraylist to integer type. So how can i do that???
ArrayList arr = new ArrayList();
String a="Mode set - In Service", b="Mode set - Out of Service";
if(line.contains(a) || line.contains(b)) {
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()) {
arr.add(st.nextToken());
}
}
Since you're using an untyped List arr, you'll need to cast to String before performing parseInt:
List<Integer> arrayOfInts = new ArrayList<Integer>();
for (Object str : arr) {
arrayOfInts.add(Integer.parseInt((String)str));
}
I recommend that you define arr as follows:
List<String> arr = new ArrayList<String>();
That makes the cast in the conversion unnecessary.
run the below code,i hope it meets you requirement.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> strArrayList= new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
int x = 0;
for (String s : strArrayList)
{
ArrayRes[i] = Integer.parseInt(s);
System.out.println(ArrayRes[i]);
i++;
}
}
}
Output:
1
11
111
12343
18475
To convert to an integer array, you will input as a string array then go through each one and change it to an int.
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
//new int for each string
int intarray[] = new int[sarray.length];
//for each int blah blah to array length i
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
final List<String> strs = new ArrayList();
strs.add("1");
strs.add("2");
Integer[] ints = new Integer[strs.size()];
for (int i = 0; i<strs.size(); i++){
ints[i] = Integer.parseInt(strs.get(i));
}
use the Integer.parseInt() method.
http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm
If you know that you have an arraylist of string but in your you wil use the same list as list of integer so better while initializing array list specify that the array list must insert only int type of data
instead of writing ArrayList arr = new ArrayList();
you could have written ArrayList<Integer> arr = new ArrayList<Integer>();
Alternate solution
If you want to convert that list into Integer ArrayList then use following code
How to convert String ArrayList into ArrayList of int
ArrayList<String> oldList = new ArrayList<String>();
oldList.add(""+5);
oldList.add(""+5);
ArrayList<Integer> newList = new ArrayList<Integer>(oldList.size());
for (String myInt : oldList) {
newList.add(Integer.parseInt(myInt));
}

Categories