Dynamically creating ArrayList inside a loop - java

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

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

How to remove repeated items of a list and copy the list into another list

I have a list of items that need to remove their repeated ones and then copy the list into another list. The problem is that I cant copy the list into the other list.
Code
.....
private List mylist = new ArrayList();
.....
LinkedHashSet hs = new LinkedHashSet();
hs.addAll(mylist);
mylist.clear();
mylist.addAll(hs);
MyClass.getItems().clear();
MyClass.setItems(mylist);
MyClass.java
.....
private List Items = new ArrayList();
public void setItems(List myItems) {
for (int i = 0; i < myItems.size(); i++) { <<This loop shows the items
System.out.println(myItems.get(i));
}
this.Items.clear();
this.Items.addAll(myItems);
for (int i = 0; i < Items.size(); i++) { << this loop does not show anything
System.out.println(Items.get(i));
}
}
Desired result
mylist >> a,b,c,a,d,c
change to a,b,c,d
then copy to items
items >> a,b,c,d
you can use a LinkedHashSet. This will preserve the insertion order and insure no duplicates.
for problem number two are you adding anyting to the list. the code you have works
List<Integer> mylist = new ArrayList<Integer>();
mylist.add(3);
mylist.add(3);
HashSet hs = new HashSet();
hs.addAll(mylist);
mylist.clear();
mylist.addAll(hs);
System.out.println(mylist.size()); //prints 1
System.out.println(hs.size());// prints 1
RESPONSE to edited question:
They both seem to print out the list fine
public class Tmp {
private List<Integer> Items = new ArrayList<Integer>();
public void setItems(List<Integer> myItems) {
for (int i = 0; i < myItems.size(); i++) { //<<This loop shows the items
System.out.println(myItems.get(i));
}
this.Items.clear();
this.Items.addAll(myItems);
System.out.println();
for (int i = 0; i < Items.size(); i++) { //<< this loop also shows the item
System.out.println(Items.get(i));
}
}
public static void main(String[] args) {
Tmp t = new Tmp();
List<Integer> myList = new ArrayList<Integer>();
myList.add(3);
myList.add(4);
t.setItems(myList);
}
}
Are both these pieces of code in the same class and both list variables pointing to the same arrayList instance. if so calling clear on one clears out both lists (since both variables are pointing to the same list)

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

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:
String dsf[] = new String[al.size()];
for(int i =0;i<al.size();i++){
dsf[i] = al.get(i);
}
But it failed saying "Ljava.lang.String;#57ba57ba"
You don't need to reinvent the wheel, here's the toArray() method:
String []dsf = new String[al.size()];
al.toArray(dsf);
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[0]);
if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
package com.v4common.shared.beans.audittrail;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String arg[]){
List<String> list = new ArrayList<String>();
list.add("abcd#xyz");
list.add("mnop#qrs");
Object[] s = list.toArray();
String[] s1= new String[list.size()];
String[] s2= new String[list.size()];
for(int i=0;i<s.length;i++){
if(s[i] instanceof String){
String temp = (String)s[i];
if(temp.contains("#")){
String[] tempString = temp.split("#");
for(int j=0;j<tempString.length;j++) {
s1[i] = tempString[0];
s2[i] = tempString[1];
}
}
}
}
System.out.println(s1.length);
System.out.println(s2.length);
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Here is the solution for you given scenario -
List<String>ls = new ArrayList<String>();
ls.add("dfsa#FSDfsd");
ls.add("dfsdaor#ooiui");
String[] firstArray = new String[ls.size()];
firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
}
This is the right answer you want and this solution i have run my self on netbeans
ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);
int b[]= new int [6];
Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
b[i]=m[i];
System.out.println(b[i]);
}
System.out.println(a.size());
This can be done using stream:
List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
List<String[]> objects = stringList.stream()
.map(s -> s.split("#"))
.collect(Collectors.toList());
The return value would be arrays of split string.
This avoids converting the arraylist to an array and performing the operation.
NameOfArray.toArray(new String[0])
This will convert ArrayList to Array in java
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
for (Integer x : arr)
System.out.print(x + " ");
}
}

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