Java fill 2d array with 1d arrays - java

Whats the nicest way to fill up following array:
From main:
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
Function I am using..:
public String[] someFunction(){
String[] out = new String[3];
return out;
}
Is it possible to do something like this? Or do I have to fill it with for-loop?
With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();

You have to specify how many rows your array contains.
String[][] data = new String[n][];
for(int i = 0; i < data.length; i++){
data[i] = someFunction();
}
Note that someFunction can return arrays of varying lengths.
Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.
I just noticed the error you got. Change your someFunction to be static.

Change your someFunction() by adding "static".
You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).
public static void main(String[] args){
int x = 3;
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
}
public static String[] someFunction(){
String[] out = new String[3];
return out;
}
Greetings Tim

Related

JAVA GET API - 2D Array, Unable to retrieve?

I am getting a data varilable through an API like this (notice square brackets):
[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
]
What I am doing wrong in the below script? I am new to Java and need to print this block in table. Please help me, thanks in advance
public class ArrayLoopTest{
public static void main(String []args){
String[] data = new String[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
];
for (i=0;i < data.length;i++) {
System.out.println(data[i]);
}
}
}
Welcome to the wold of java.
Here are some things that you seem not to be doing well, as you know java is a strongly typed language. However from your code you are using a float in your array . perhaps you have declared that your array will contain strings only.
More so you are not declaring your array in a right way.
I will recommend that you work through this tutorial quickly Arrays in java.
But to resolve your issue you can do this instead
p
ublic static void main(String []args){
String[][] data = new String[][]{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
};
for (int i=0;i < data.length;i++) {
for (int j = 0; j < data[i].lenght(); i++){
` System.out.print(data[i][j] + " ");
}
System.out.println("--------------")
}
}
While using an array keep in mind that array data structure can hold data of one type only. This essentially means that if a array is declared as String then it can have String type data only.
So, you can use the following code defining and printing the 2D array.
public static void main(String[] args) {
String[][] data = {
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"}
,{"2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"}
,{"2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for(int i=0;i<data.length;i++) {
for(int j=0;j<data[i].length;j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
// or you can print like this
for(int i=0;i<data.length;i++) {
System.out.println(Arrays.toString(data[i])+",");
}
}
Edit:
You can use the com.google.gson library as shown below to get a 2D array:
//String apiResponse = get Api Response
JsonParser parser = new JsonParser(); // parser converstthe api response to Json
JsonObject obj = (JsonObject) parser.parse(apiResponse);
JsonObject obj1 = obj.getAsJsonObject("dataset");
JsonArray arr = obj1.get("data").getAsJsonArray();
String[][] newString = new String[arr.size()][arr.get(0).getAsJsonArray().size()];
for(int i=0;i<newString.length;i++) {
for(int j=0;j<newString[i].length;j++) {
newString[i][j] = arr.get(i).getAsJsonArray().get(j).getAsString();
}
}
System.out.println(Arrays.deepToString(newString));
It can be solved in two ways, one dimensional and two dimensional, if you are thinking to put different data types in a single array, that is not possible in java.You can put only one type of data type inside defined array type.
Two dimensional array code:
public class ArrayLoopTest{
public static void main(String []args){
String[][] data =
{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{ "2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"},
{ "2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for (int i=0;i < data.length;i++) {
{
for(int j=0;j<data[i].length;j++)
{
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
}}
One dimensional array code
public class ArrayLoopTest{
public static void main(String []args){
String[] data ={"2018-09-03,287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35",
"2018-08-31,286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41",
"2018-08-30,286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03"};
for (int i=0;i < data.length;i++)
{
System.out.println(data[i]);
}
}}
This won't compile as your array isn't of the correct format and the variable i is not defined. You need to loop over the items in each subarray and print them instead.
String[][] data = new String[][]{
{ "2018-09-03", "287.5", "289.8", "286.15", "287.3", "287.65", "1649749.0", "4750.35" },
{ "2018-08-31", "286.25", "290.5", "285.0", "285.5", "285.95", "3716997.0", "10691.41" },
{ "2018-08-30", "286.45", "290.55", "284.6", "286.05", "285.6", "3861403.0", "11097.03" }
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.print("\n");
}

Trying to flip an array around but keep getting an error

Attempting to test and see if an array is a palindrome, however, the flipArray method I created keeps giving me trouble. The compiler gives a "not a statement" error and I'm not sure what is stopping it. The code is supposed to flip array b around, then compare array a and array b to see if they are the same:
public class Lab13_2{
public static final int SIZE = 50;
public static void main (String [] args){
Boolean palindrome = false;
String[] a = {"hello" , "goodbye", "goodbye" , "hello"};
String[] b = new String[SIZE];
b = a.clone();
palindrome = getPalindrome(a,b,a.length);
}
public static boolean getPalindrome(String[] a, String[] b, int arrayLength{
b = flipArray(b);
for(int i = 0; i <arrayLength; i++){
if(a[i] != b[i]){
return false;
}
}
return true;
}
public static String[] flipArray(String[] array){
for(int=0; i <array.length/2; i++){
int temp = array[i];
array[i] = array[array.length-1-i];
array[array.length-1-i] = temp;
}
return array;
}
}
you're missing the closing ) for the getPalindrome method.
your for loop within the flipArray method doesn't declare i before it's used within the condition or elsewhere. should be for(int i = 0; i < array.length/2; i++).
your temp variable should be of type String rather than int.
Lastly but not least you don't compare strings like this:
if(a[i] != b[i])
change it to this:
if(!a[i].equals(b[i]))

How can I convert List<List<String>> into String[][]?

In my project I have a List that contains Lists of Strings (List<List<String>>) and now I have to convert this List into an array of String arrays (String[][]).
If I had a single List<String> (for example myList) then I could do this to convert to String[]:
String[] myArray = new String[myList.size()];
myArray = myList.toArray(myArray);
But in this case I have lots of List of String inside a List (of List of Strings).
How can I do this? I've spent lots of time but I didn't find a solution..
I wrote a generic utility method few days back for my own usage, which converts a List<List<T>> to T[][]. Here's the method. You can use it for your purpose:
public static <T> T[][] multiListToArray(final List<List<T>> listOfList,
final Class<T> classz) {
final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);
for (int i = 0; i < listOfList.size(); i++) {
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
}
return array;
}
There I've created the array using Array#newInstance() method, since you cannot create an array of type parameter T directly.
Since we're creating a 2-D array, and we don't yet know how many columns you will be having, I've given the column size as 0 initially. Anyways, the code is initializing each row with a new array inside the for loop. So, you don't need to worry about that.
This line:
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
uses the List#toArray(T[]) method to convert the inner list to an array, as you already did. I'm just passing an array as a parameter to the method so that the return value which I get is T[], which I can directly assign to the current row - array[i].
Now you can use this method as:
String[][] arr = multiListToArray(yourList, String.class);
Thanks to #arshaji, you can modify the generic method to pass the uninitialized array as 2nd parameter, instead of Class<T>:
public static <T> void multiListToArray(final List<List<T>> listOfList,
final T[][] arr) {
for (int i = 0; i < listOfList.size(); ++i) {
arr[i] = listOfList.get(i).toArray(arr[i]);
}
}
But then, you have to pass the array to this method like this:
List<List<String>> list = new ArrayList<>();
// Initialize list
String[][] arr = new String[list.size()][0];
multiListToArray(list, arr);
Note that, since now we are passing the array as argument, you no longer need to return it from your method. The modification done in the array will be reflected to the array in the calling code.
String[][] myArray = new String[myList.size()][];
for (int i = 0; i < myList.size(); i++) {
List<String> row = myList.get(i);
myArray[i] = row.toArray(new String[row.size()]);
}
Here is one way
List<List<String>> list = new ArrayList<List<String>>();
String[][] array = new String[list.size()][];
int counter1 = 0;
for(List<String> outterList : list)
{
array[counter1] = new String[outterList.size()];
int counter2 = 0;
for(String s : outterList)
{
array[counter1][counter2] = s;
counter2++;
}
counter1++;
}
To init String[][], you should init the list(array) of String[]
So you need to define a list
List<String[]> string = new List<String[]>();
for (int i = 0;....)
{
String[] _str = new String[numbers];
_str[0] = ...
string.append(_str);
}

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

ArrayList filled with 1D Arrays, cant access Values in Arrays

I'm putting 1D Arrays in an Array List
ArrayList<int[]> pairs_ref = new ArrayList();
int[]singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
However, an test output on the console only shows Zeros, not the correct values
pairs_ref = object_ref.methodFillsArrayListAsShownAbove();
for (int t = 0;t<pairs_ref.size();t++){
int[]array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
}//endfor
this Version brings the same result
int[]array_ref = new int[2];
for (int t = 0;t<pairs_ref.size();
array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
System.out.println(pairs_ref.get(t));}
Why is this? Is it the putting or the getting of the variables of the ArrayList?
Thanks in Advance!
Daniel
If this is the observed output for you, something else is wrong in your code.
The program below (verbatim copy of the snippets you provided) outputs the expected result:
import java.util.*;
class Test {
public static ArrayList<int[]> methodFillsArrayListAsShownAbove() {
ArrayList<int[]> pairs_ref = new ArrayList();
int[] singlePair_ref = new int[2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
}
public static void main(String[] args) {
List<int[]> pairs_ref = methodFillsArrayListAsShownAbove();
for (int t = 0; t < pairs_ref.size(); t++) {
int[] array_ref = pairs_ref.get(t);
System.out.println("Live: " + array_ref[0] + " " + array_ref[1]);
}// endfor
}
}
Output:
Live: 15 0
Ideone.com demo
Link
Note that as of Java 5 your code can be simplified:
ArrayList<int[]> pairs_ref = new ArrayList<int[]>(); //note the use of generics in the parameter
int[] singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
//simplification here
for (int[] arr : pairs_ref){
System.out.println("Live: "+arr[0]+" "+arr[1]);
}
This should work at your system.

Categories