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>>.
Related
How might I convert an ArrayList<String> object to a String[] array in Java?
List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.
Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
Starting from Java-11, one can use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:
List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
You can use the toArray() method for List:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = list.toArray(new String[list.size()]);
Or you can manually add the elements to an array:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Hope this helps!
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
Using copyOf, ArrayList to arrays might be done also.
In Java 8:
String[] strings = list.parallelStream().toArray(String[]::new);
In Java 8, it can be done using
String[] arrayFromList = fromlist.stream().toArray(String[]::new);
If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
There are a few more preallocated empty arrays of different types in ArrayUtils.
Also we can trick JVM to create en empty array for us this way:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
But there's really no advantage this way, just a matter of taste, IMO.
You can use Iterator<String> to iterate the elements of the ArrayList<String>:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Now you can retrive elements from String[] using any Loop.
Generics solution to covert any List<Type> to String []:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString() method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String [] strArry= list.stream().toArray(size -> new String[size]);
Per comments, I have added a paragraph to explain how the conversion works.
First, List is converted to a String stream. Then it uses Stream.toArray to convert the elements in the stream to an Array. In the last statement above "size -> new String[size]" is actually an IntFunction function that allocates a String array with the size of the String stream. The statement is identical to
IntFunction<String []> allocateFunc = size -> {
return new String[size];
};
String [] strArry= list.stream().toArray(allocateFunc);
List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
array[i++] = s;
}
in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:
import java.util.ArrayList;
import java.lang.reflect.Array;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
public static <T> T[] convert(ArrayList<T> al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}
In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
from java.base's java.util.Collection.toArray().
You can convert List to String array by using this method:
Object[] stringlist=list.toArray();
The complete example:
ArrayList<String> list=new ArrayList<>();
list.add("Abc");
list.add("xyz");
Object[] stringlist=list.toArray();
for(int i = 0; i < stringlist.length ; i++)
{
Log.wtf("list data:",(String)stringlist[i]);
}
private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
String[] delivery = new String[deliveryServices.size()];
for (int i = 0; i < deliveryServices.size(); i++) {
delivery[i] = deliveryServices.get(i).getName();
}
return delivery;
}
An alternate one-liner method for primitive types, such as double, int, etc.:
List<Double> coordList = List.of(3.141, 2.71);
double[] doubleArray = coordList.mapToDouble(Double::doubleValue).toArray();
List<Integer> coordList = List.of(11, 99);
int[] intArray = coordList.mapToInt(Integer::intValue).toArray();
and so on...
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);
}
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()]);
}
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]);
}
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));
}