Convert two dimensional array to List in java?
This is a nice way of doing it for any two-dimensional array, assuming you want them in the following order:
[[array[0]-elems], [array[1]elems]...]
public <T> List<T> twoDArrayToList(T[][] twoDArray) {
List<T> list = new ArrayList<T>();
for (T[] array : twoDArray) {
list.addAll(Arrays.asList(array));
}
return list;
}
How to convert 2Darray into 2D ArrayList in java?
I would suggest 3 improvements in your code.
use
array2D[i].length
instead ofarray2D[1].length
.use
eachRecord.add(String.valueOf(array2D[i][j]));
instead ofeachRecord.add(String.valueOf(array2D[j]));
.
array2D[index]
returns a total array. array2D[indexRow][indexCol]
returns the object at those indexes.
- Instead of clear() initiate the eachRecord list inside the loop.
List<String> eachRecord = new ArrayList<String>();
inside the first for
loop.
String [][]array2D = {{"A", "B"}, {"C", "D"}, {"E", "F"}};
List<List<String>> arrayList2D = new ArrayList<List<String>>();
for (int i = 0; i < array2D.length; i++) {
List<String> eachRecord = new ArrayList<String>();
for (int j = 0; j < array2D[i].length; j++) {
eachRecord.add(String.valueOf(array2D[i][j]));
}
arrayList2D.add(eachRecord);
}
System.out.println(arrayList2D);//[[A, B], [C, D], [E, F]]
If you want to add whole array you could use Arrays#asList
method.
String[][] array2D = { { "A", "B" }, { "C", "D" }, { "E", "F" } };
List<List<String>> arrayList2D = new ArrayList<List<String>>();
for (int i = 0; i < array2D.length; i++) {
List<String> eachRecord = Arrays.asList(array2D[i]);
arrayList2D.add(eachRecord);
}
System.out.println(arrayList2D);
Transfer a Two-Dimensional array to Two-Dimensional ArrayList?
Case 1 It is short, but need to covert the primitive type to reference type (int
to Integer
) as needed for Arrays.asList();
Integer[][] pattern = new Integer[][]{
{ 1, 1, 1, 1, 1, 1, 1 },
{ 1, 2, 0, 0, 0, 2, 1 },
{ 1, 0, 3, 0, 3, 0, 1 },
{ 1, 0, 0, 4, 0, 0, 1 },
{ 1, 0, 3, 0, 3, 0, 1 },
{ 1, 2, 0, 0, 0, 2, 1 },
{ 1, 1, 1, 1, 1, 1, 1 },
};
List<List<Integer>> lists = new ArrayList<>();
for (Integer[] ints : pattern) {
lists.add(Arrays.asList(ints));
}
Case 2 If you don't want to covert the primitive type to reference type: (int[][] pattern = new int[][]
to Integer[][] pattern = new Integer[][]
)
List<List<Integer>> lists = new ArrayList<>();
for (int[] ints : pattern) {
List<Integer> list = new ArrayList<>();
for (int i : ints) {
list.add(i);
}
lists.add(list);
}
Casting 2d Array to List of lists in Java
The only faster way to do this would be with a fancier view; you could do this with Guava like so:
Double[][] array;
List<List<Double>> list = Lists.transform(Arrays.asList(array),
new Function<Double[], List<Double>>() {
@Override public List<Double> apply(Double[] row) {
return Arrays.asList(row);
}
}
}
That returns a view in constant time.
Short of that, you already have the best solution.
(FWIW, if you do end up using Guava, you could use Doubles.asList(double[])
so you could use a primitive double[][]
instead of a boxed Double[][]
.)
Convert two-dimensional ArrayList to two-dimensional array
You can do it as follows:
int[][] arr = list.stream()
.map(l -> l.stream()
.mapToInt(Integer::intValue)
.toArray())
.toArray(int[][]::new);
Each inner List
is mapped to an int[]
(by first converting it to an IntStream
), and then you convert your Stream<int[]>
to an int[][]
.
Convert two dimensional array to List in java?
This is a nice way of doing it for any two-dimensional array, assuming you want them in the following order:
[[array[0]-elems], [array[1]elems]...]
public <T> List<T> twoDArrayToList(T[][] twoDArray) {
List<T> list = new ArrayList<T>();
for (T[] array : twoDArray) {
list.addAll(Arrays.asList(array));
}
return list;
}
Convert ArrayList into 2D array containing varying lengths of arrays
String[][] array = new String[arrayList.size()][];
for (int i = 0; i < arrayList.size(); i++) {
ArrayList<String> row = arrayList.get(i);
array[i] = row.toArray(new String[row.size()]);
}
where arrayList
is your ArrayList<ArrayList<String>>
(or any List<List<String>>
, change the first line inside the for
loop accordingly)
How can I convert a 2D array to a 2D list with Streams?
Arrays.stream
will go through each int[]
in the int[][]
.
You can convert an int[]
to an IntStream
.
Then, in order to convert a stream of int
s to a List<Integer>
,
you first need to box them.
Once boxed to Integer
s, you can collect them to a list.
And finally collect the stream of List<Integer>
into a list.
List<List<Integer>> list = Arrays.stream(data)
.map(row -> IntStream.of(row).boxed().collect(Collectors.toList()))
.collect(Collectors.toList());
Demo.
Convert a 2D array into a 1D array
You've almost got it right. Just a tiny change:
public static int mode(int[][] arr) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
// tiny change 1: proper dimensions
for (int j = 0; j < arr[i].length; j++) {
// tiny change 2: actually store the values
list.add(arr[i][j]);
}
}
// now you need to find a mode in the list.
// tiny change 3, if you definitely need an array
int[] vector = new int[list.size()];
for (int i = 0; i < vector.length; i++) {
vector[i] = list.get(i);
}
}
assigning each value from the list to a two-dimensional array
A for-loop with another nested one shall do the thing:
List<String> list = ... // input list
int[][] tab = new int[2][3]; // target array
int outerIndex = 0; // X-index of tab[X][Y]
for (String line: list) { // for each line...
String[] stringArray = line.split(" "); // ... split by a space
int innerIndex = 0; // ... Y-index of tab[X][Y]
for (String str: stringArray) { // ... for each item in a line
int number = Integer.parseInt(str); // ...... parse to an int
tab[outerIndex][innerIndex++] = number; // ...... add to array tab[X][Y]
} and increase the Y
outerIndex++; // ... increase the X
}
Remember, additionally, you might want:
- ... to handle the exceptional values (non-parseable into an int)
- ... to split by multiple white characters (
\\s+
), not a single space - ... to handle the array index overflow
The Java 8 Stream API brings the way easier way to do so... if you don't mind Integer[][]
as a result instead.
Integer[][] tab2 = list.stream() // Stream<String>
.map(line -> Arrays.stream(line.split(" ")) // ... Stream<String> (split)
.map(Integer::parseInt)) // ... Stream<Integer>
.toArray(Integer[]::new)) // ... Integer[]
.toArray(Integer[][]::new); // Integer[][]
Related Topics
Setting Print Size of a Jlabel and Put a Jradiobutton on the Print
How to Set Order of Repositories in Maven Settings.Xml
How to Convert Int[] to Byte[]
How to Clone a Generic List in Java
Why Does Java Code with an Inner Class Generates a Third Someclass$1.Class File
Java.Rmi.Connectexception: Connection Refused to Host: 127.0.1.1;
Converting a String to Color in Java
Why Are Wait() and Notify() Declared in Java's Object Class
Accessing a File Inside a .Jar File
String S = New String("Xyz"). How Many Objects Has Been Made After This Line of Code Execute
Changing Java Platform on Which Netbeans Runs
Checking If Unlimited Cryptography Is Available
Creating Runnable Jar with External Files Included
How to Convert "Mon Jun 18 00:00:00 Ist 2012" to 18/06/2012
How to Apply Multiple Predicates to a Java.Util.Stream