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

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]);
}

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>>.

Moving data to different methods

I am trying to figure out how to save a data in a submethod several times.
For example the code below is creating and array of strings then the array is moved to an arraylist five times. How to make the program save all strings 5 times. With other words, if I print out the array list newList .How to get the following output?
word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4.
public static void main(String[] args) {
String[] list = new String[5];
for (int i = 0; i < list.length; i++) {
list[i] = "word" + i;
}
for (int i = 0; i < 5; i++) {
experiment(list);
}
}
public static void experiment(String[] list) {
ArrayList<String> arrList = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
arrList.add(list[i]);
}
saveItAll(arrList);
}
public static ArrayList<String> saveItAll(ArrayList<String> counter) {
ArrayList<String> newList = new ArrayList<>();
newList = counter;
System.out.println(newList);
return newList;
}
You need to store it outside of the method and statically.
public class Test
{
static List<String> newList = new ArrayList<>();
public static void main(String[] args)
{
String[] list = new String[5];
for (int i = 0; i < list.length; i++) {
list[i] = "word" + i;
}
for (int i = 0; i < 5; i++) {
experiment(list);
}
System.out.println(newList);
}
public static void experiment(String[] list)
{
List<String> arrList = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
arrList.add(list[i]);
}
saveItAll(arrList);
}
public static void saveItAll(List<String> counter)
{
newList.addAll(counter);
}
}
Another word here: You would not need the saveItAll method, since addAll is also doing the job here. Then you usually don't use Lists with there implementing type, you usually use the interface to define the type of it so the implementation would be switchable. That's what interfaces are for.

Printing empty brackets?

I have a simple program that should take two arrays, convert them into lists, and take out the values that are the same. For some reason though I am getting a value of:
[]
[]
[]
[]
Although the result should be "eggs", "lasers", "hats", "pie" - "lasers", "hats" which should get me a result of "eggs" "pie".
Here is my code:
public class Arraystring {
public static void main(String[] args) {
String[] things = { "eggs", "lasers", "hats", "pie" };
List<String> list1 = new ArrayList<String>();
for (String x : things) {
list1.add(x);
}
String[] thingstwo = { "lasers", "hats" };
List<String> list2 = new ArrayList<String>();
for (int i = 0; i < list2.size(); i++) {
list2.add(thingstwo[i]);
}
editlist(list1, list2);
}
public static void editlist(Collection<String> l1, Collection<String> l2) {
Iterator<String> it = l1.iterator();
while (it.hasNext()) {
if (l2.contains(it.next())) {
System.out.println("hui");
it.remove();
}
System.out.println(l2);
}
}
}
First your line in Arraystring {..}
for (int i = 0; i < list2.size(); i++) {
should be
for (int i = 0; i < thingstwo.length; i++) {
And then you are printing the wrong list in editlist(..):
System.out.println(l2);
should be
System.out.println(l1);

How to iterate through two dimensional ArrayList using iterator?

I would like to iterate through two dimensional ArrayList which includes String objects using iterator. I also would like to iterate in a way that let me choose whether I want to iterate horizontally(row) first or vertically(column) by using a boolean value. How can I implement this in java?
What I've tried so far.
public class IterateThis implements Iterator<String>{
ArrayList<ArrayList<String>> array;
public IterateThis(){
array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
}
Iterator<String> it = array.iterator(); //This gives me an error...why?
I don't know how I can implement the boolean value though.
Maybe you need to implement two versions, with a boolean that decides which loop to use:
public void iterate(boolean horizantalFirst){
if(horizontalFirst){
for(int i=0; i<array.size(); i++){ // first iterate through the "outer list"
for(int j=0; j<array.get(i).size(); j++){ // then iterate through all the "inner lists"
array.get(i).get(j)="1";
}
}
}else{
int j=0; // index to iterate through the "inner lists"
for(; j<array.get(j).size(); j++){ //dangerous, you need to be sure that there is a j-th element in array
for(int i=0; i<array.size(); i++){ // iterate here through the outer list, by always working on the j-th element
array.get(i).get(j)="1";
}
}
}
}
Why not try this:
import java.util.ArrayList;
public class Iteration
{
private ArrayList<ArrayList<String>> array;
public Iteration()
{
array = new ArrayList<>();
array.add(new ArrayList<String>());
array.get(0).add("000");
array.get(0).add("001");
array.get(0).add("010");
array.add(new ArrayList<String>());
array.get(1).add("100");
array.get(1).add("101");
array.get(1).add("110");
array.get(1).add("111");
iterateRowWise();
System.out.println("\n\n");
iterateColumnWise();
}
public void iterateRowWise()
{
// This uses iterator behind the scene.
for (ArrayList<String> row : array)
{
for (String element : row)
{
System.out.print(element + " ");
}
System.out.println();
}
}
public void iterateColumnWise()
{
int arraySize = array.size();
int maxColumns = getMaximumListSize();
for (int c = 0; c < maxColumns; c++)
{
for (int r = 0; r < arraySize; r++)
{
ArrayList<String> rowList = array.get(r);
if (c < rowList.size())
{
System.out.print(rowList.get(c) + " ");
}
}
System.out.println();
}
}
private int getMaximumListSize()
{
int maxListSize = 0;
for (ArrayList<String> rowList : array)
{
if (maxListSize < rowList.size())
maxListSize = rowList.size();
}
return maxListSize;
}
public static void main(String[] args)
{
new Iteration();
}
}
The iterateRowWise() method iterates using the iterator, but it does so behind the scene.
The iterateColumnWise() method doesn't use iterator, but its safe to use.
Row-wise iteration is simple as shown in the #Awfully Awesome answer.
Tried a columnwise iteration with assumption that List will always have m cross n elements where m=n
public static void IterateThis() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
Iterator<ArrayList<String>> it = array.iterator();
int topLevelIteratorResetCounter = 0;
int noOfIteratorNextRequired = 1;
int size = array.size();
while (it.hasNext()) {
ArrayList<String> strList = it.next();
if (noOfIteratorNextRequired > strList.size())
break;
Iterator<String> itString = strList.iterator();
int numtimes = 0;
String str = null;
while (numtimes != noOfIteratorNextRequired) {
str = itString.next();
numtimes++;
}
System.out.println(str);
numtimes = 0;
topLevelIteratorResetCounter++;
if (topLevelIteratorResetCounter == size) { //as column count is equal to column size
it = array.iterator(); //reset the iterator
noOfIteratorNextRequired++;
topLevelIteratorResetCounter = 0;
}
}
}
The answer uses Iterator.

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

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()]);
}

Categories