Extract String arrays from List - java

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

Related

Object[] cannot be cast to String[] after using toarray() method [duplicate]

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

ArrayList iteration specific list

I have an arraylist in which
ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();
in the list of items I have items like this
[[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22]]
how to iterate and store in another array these values split into two like
[1,2,3,4,5,6,7,8,9,10,11] and [11,12,13,14,15,16,17,18,19,20,21,22]. I have used advanced for loop
for(ArrayList<String> list:listofItems)
{
for (String s:list)
{
//I dont know how to add logic here.
}
}
I am assuming here that both lists will also hold string type data.If you want Integer type,you can parse while adding.
ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
for (ArrayList<String> list : listofItems) {
for (String s : list) {
// there shud be some condition how much elements you want in a
// list or some condition
// to decide in which list we need to add item
if (list.size() < 12)
list1.add(s);
else
list2.add(s);
}
}
Use something like that:
if (yourlist.size()>0) {
List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}
Would be separate your list in 2 lists divided in the half.
You can use this code to store your list into another list.
List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
for (String s:list) {
stringList.add(s);
}
}
In this case, when you add info to listOfItems, you should try example like this
for(int i = 0; i< 2; i++){
for(int j = 0; j < n; j++){
/// add util break n
lists.get(i).add(strTemp);
}
}
You can change i < 2 into any number you want. I only make this sample for you.

Converting List<ArrayList> to String[]

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

get String from ArrayList

How to get String from ArrayList if my code like
ArrayList<String> PItoList = new ArrayList();
for (int i = 0; i < AllPunchList.size(); i++) {
PItoList.add(AllPunchList.get(i).toString());
}
I want to split item in ArrayList one by one.
You could do something like this:-
for(String eachString : PItoList){
// eachString.split(regex);
}
Traverse through each element in the List and do whatever you want to do in with each Element!
Try this :-
ArrayList<String> PItoList = new ArrayList<String>();
for (int i = 0; i < AllPunchList.size(); i++) {
PItoList.add((String)AllPunchList.get(i));
}
In the above example I have printed all elements in ArrayList. In this manner you can get all elements.
Then why you need split ?
Hope it will help you.

Converting 'ArrayList<String> to 'String[]' in Java

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

Categories