Java convert ArrayList<String[]> to String[][] - java

Do I have to loop through each element to convert ArrayList<String[]> to String[][] or is there a more efficient way?

Just get the contents as an array
List<String[]> list = new ArrayList<>();
...
String[][] array = list.toArray(new String[0][0]); // the size here is not important, the array is just an indication of the type to use

You can use .toArray(T[]) for this.
public static void main(String[] args) {
List<String[]> l = new ArrayList<String[]>();
String[] a = {"lala", "lolo"};
String[] b = {"lili", "lulu"};
l.add(a);
l.add(b);
String[][] r = new String[l.size()][];
r = l.toArray(r);
for(String[] s : r){
System.out.println(Arrays.toString(s));
}
}
Output:
[lala, lolo]
[lili, lulu]

Related

How to split strings of list into string array

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?
You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}
For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

Converting Arraylist to an Array [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...

Convert List<String[]> to int[]

If it's possible to convert arraylist of string (ArrayList<String[]>) to array of integer (int[]), is it possible to convert arraylist of arrays of string(ArrayList<String[]>) to array of integer (int[])?
In Java 8:
list.stream().mapToInt(Integer::parseInt).toArray();
edit
Since the question was edited with List<String[]> instead of List<String>, a solution would be:
list.stream().flatMap(Arrays::stream).mapToInt(Integer::parseInt).toArray();
i have modified the code according to your edited answer,do reply if this is what you want.
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[]>();
String[] str1={"16","1421","1577"};
String[] str2={"15","1451","1461","6556"};
String[] str3={"157","8751","1136","556","879"};
strArrayList.add(str1);
strArrayList.add(str2);
strArrayList.add(str3);
int sizeOfArr=0;
int i=0;
for (String[] s : strArrayList)
{
sizeOfArr+=s.length;
}
int[] ArrayRes = new int[sizeOfArr];
for (String[] s : strArrayList)
{
if(s.length>0){
for (String s1 : s){
ArrayRes[i] = Integer.parseInt(s1);
System.out.println(ArrayRes[i]);
i++;
}
}
}
}
}
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
Further to my comment, you'll need to work out how to map from 2D to 1D array.
Here's a suggestion which results in Integer[] rather than int[] but you might not worry about that:
public static void main(String[] args) {
ArrayList<String[]> arrList = new ArrayList<String[]>();
//fill it
arrList.add(new String[] {"11","12","13","14","15"});
arrList.add(new String[] {"21","22","23","24","25"});
arrList.add(new String[] {"31","32","33","34","35"});
arrList.add(new String[] {"41","42","43","44","45"});
arrList.add(new String[] {"41","52","53","54","55"});
//convert it
ArrayList<Integer> ints = new ArrayList<Integer>();
for (String[] array : arrList) {
for (String str : array) {
ints.add(Integer.parseInt(str));
}
}
Integer[] result = ints.toArray(new Integer[] {});
for (int i : result)
System.out.println(i);
}
It is possible if all the Strings can be parsed to integers correctly.
Iterate over the list and in the list over the array. Parse the Strings to Integers (e.g. with Integer.parseInt(someString);) and store the integervalues in the integer array.
Of course you'll have to find the total number of values in the list to initialize the array.

Array structure in java

Can I create an array like this in java???
Array
([0]
array
[items1] = "one"
[items2] = "two"
[items3] = "three")
([1]
array
[items1] = "one###"
[items2] = "two###"
[items3] = "three#")
Thanx for your help
Yes, you can do this by creating an array of arrays. For example:
String[][] twoDimensionalPrimitiveArray = {
{"one", "two", "three"},
{"one###", "two###", "three###"}
};
You can also do this with the collection types:
List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));
// ...
private static List<String> createList(String... values) {
List<String> result = new ArrayList<>();
for (String value : values) {
result.add(value);
}
return result;
}
Edit
#immibis has rightly pointed out in the comments that createList() can be written more simply as new ArrayList(Arrays.asList(values)).
Yes, you can define an array of arrays:
String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
arrayOfArrays[0] = new String[3]; // initialize first array
arrayOfArrays[1] = new String[3]; // initialize second array
// fill arrays
arrayOfArrays[0][0] = "one";
arrayOfArrays[0][1] = "two";
arrayOfArrays[0][2] = "three";
arrayOfArrays[1][0] = "one###";
arrayOfArrays[1][1] = "two###";
arrayOfArrays[1][2] = "three#";
And to test it (print values):
for (String[] array : arrayOfArrays) {
for (String s : array) {
System.out.print(s);
}
System.out.println();
}
For two dimension arrays in Java you can create them as follows:
// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};
Alternatively you can define the array and then fill in each element but that is more tedious, however that may suit your needs more.
// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";
String[] twoDArray[] = {{"one", "two", "three"}, {"one###", "two###", "three###"}};

Print a string from ArrayList of String[]?

I have an ArrayList full of strings arrays that I built like this:
String[] words = new String[tokens.length];
I have three arrays like above in my ArrayList:
surroundingWords.add(words);
surroundingWords.add(words1);
surroundingWords.add(words2);
etc
Now if I want to print out the elements in the String arrays within surroundingWords... I can't.
The closest I can get to displaying the contents of the String[] arrays is their addresses:
[Ljava.lang.String;#1888759
[Ljava.lang.String;#6e1408
[Ljava.lang.String;#e53108
I've tried a lot of different versions of what seems to be the same thing, the last try was:
for (int i = 0; i < surroudingWords.size(); i++) {
String[] strings = surroundingWords.get(i);
for (int j = 0; j < strings.length; j++) {
System.out.print(strings[j] + " ");
}
System.out.println();
}
I can't get past this because of incompatible types:
found : java.lang.Object
required: java.lang.String[]
String[] strings = surroundingWords.get(i);
^
Help!
I've already tried the solutions here: Print and access List
Try something like this
public class Snippet {
public static void main(String[] args) {
List<String[]> lst = new ArrayList<String[]>();
lst.add(new String[] {"a", "b", "c"});
lst.add(new String[] {"1", "2", "3"});
lst.add(new String[] {"#", "#", "!"});
for (String[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
Cast the Object into a String[]:
String[] strings = (String[]) surroundingWords.get(i);
or use a parameterized ArrayList:
ArrayList<String[]> surroundingWords = new ArrayList<String[]>();
Then you won't have to cast the return value from get().

Categories

Resources