What is the easiest way to convert a Java ArrayList to Object[][]?
For example:
List<MyClass> myList = new ArrayList<MyClass>();
myList.add(myObj1);
myList.add(myObj2);
Object[][] objArray = myList.... How do I convert?
The reason I'm trying to do this is to use the QueryRunner.batch(String sql, Object[][] params) method of DBUtils.
EDIT:
See here for details:
DBUtils QueryRunner.batch()
EDIT2:
I'll try to give some more information.
public class MyObj
{
int myInt;
String myString;
}
MyObj obj1 = new MyObj(1, "test1");
MyObj obj2 = new MyObj(2, "test2");
List<MyObj> myList = new ArrayList<MyObj>();
myList.add(obj1);
myList.add(obj2);
Object[] onedArray = myList.toArray(); // Now I have a 1d array of my list of objects.
Object[] objArray = myList.get(0); // How do I convert each object instance into an array of Objects?
// Intended result would be something like this:
new Object[][] { { 1, "test1" }, { 2, "test2" } };
EDIT3:
One possible solution is this:
I could add a toObjectArray() method to MyObj class.
Surely there must be a better way?
public Object[] toObjectArray()
{
Object[] result = new Object[2];
result[0] = this.myInt;
result[1] = this.myString;
return result;
}
Thanks.
Arraylist is a single dimensional collection because it uses a single dimensional array inside. You cannot convert a single dimensional array to a two dimensional array.
You may have to add more information in case you want to do conversion of 1D to 2D array.
Related
If you are using TestNG you would find that to use a method as a data provider you have to create a method that returns a two dimensional Object array.
So if I have a List of (say) Students , is there any utility method to convert it into a two dimensional array.
I am NOT looking to convert it manually using a loop like this
List<Student> studentList = getStudentList();
Object [][] objArray = new Object[studentList.size][];
for(int i=0;i< studentList.size();i++){
objArray[i] = new Object[1];
objArray[i][0] = studentList.get(i);
}
return objArray;
Instead I am looking at a utility function if any is available in any of the libraries.
Or a better way of writing a data provider method for TestNG
With Java 8 streams (and using this question about converting a stream into array):
#DataProvider
public Object[][] studentProvider() {
return studentList.stream()
.map(student -> new Object[] { student })
.toArray(Object[][]::new);
}
So be it ... let stackoverflow call me a tumbleweed ... but here is the answer.
List<Student> studentList = getStudentList();
Object [][] objArray = new Object[studentList.size][];
for(int i=0;i< studentList.size();i++){
objArray[i] = new Object[1];
objArray[i][0] = studentList.get(i);
}
return objArray
This is not directly answer your question. But you can also solve that problem like this
#DataProvider
public Iterator<Object[]> studentProvider() {
List<Student> students = getStudentList();
Collection<Object[]> data = new ArrayList<Object[]>();
students.forEach(item -> data.add(new Object[]{item}));
return data.iterator();
}
IT worked for me in single dimension array also, I converted list to single dimension array in testng data provider, Might be useful to someone
#DataProvider(name = "Passing List Of Maps")
public Object[] createDataforTest3(){
TestDataReader testDataReader = new TestDataReader();
List<String> caselDs = new ArrayList<String>();
caselDs = testDataReader.getValueForThekeyFromTestDataDirectory("testdate,"XYZ");
Object[] data = new String[caseIDs.size()];
for (int i=0;i<caseIDs.size()-1;i++) {
data[i]= caselDs.get(i);
return data;}
#Test(dataProvider = "Passing List Of Maps",description= "abc")
public void test(String value) {
System.out.println("Value in first Map:" + value);
}
I was wondering how exactly to create an ArrayList of an array of objects. For example
Object[] objectArray = new Object() // Varying amount of object[]
I would like to add Object[] to an ArrayList as they come in. I have seen that an ArrayList of arrays can be created by the following:
ArrayList<String[]> action = new ArrayList<String[]>();
So I was thinking it would be as simple as:
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
But apparently not.
You create an ArrayList of arrays this way :
ArrayList<Object[]> action = new ArrayList<Object[]>();
Each time you add an Object[] to that list, it must have a fixed length.
If you want variable length arrays inside the ArrayList, I suggest you use ArrayList<ArrayList<Object>>.
Your syntax with objectArray is simply not valid Java syntax.
The type parameter in the generic List class should be the class name and not the name of the variable that references the array:
ArrayList<Object[]> action = new ArrayList<Object[]>();
Two notes:
Try to avoid declaring types to the implementations. Declare action as a List (the interface):
List<Object[]> action = new ArrayList<Object[]>();
It would make life a bit easier if you make the parameter another List instead of an array of Objects:
List<List<?>> action = new ArrayList<List<?>>();
ArrayList<LoadClass[]> sd = new ArrayList<LoadClass[]>();
This works :)
So, you have two questions:
Object[] objectArray = new Object()
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
Change it to:
int MAX_ARRAY = 3;
Object[] objectArray = new Object[MAX_ARRAY];
ArrayList<Object[]> action = new ArrayList<Object[]>();
Now you can add your objectArray to "action":
action.add(objectArray);
It's a easy stuff.
// Class Student with a attribute name
public class Student{
String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public static void main(String[] args) {
// Creating an ArrayList for Students
ArrayList<Student> students = new ArrayList<Student>();
// Creating an Students Objects
Student a1 = new Student("Name1");
Student a2 = new Student("Name2");
Student a3 = new Student("Name3");
// Populating ArrayList<Student>
students.add(a1);
students.add(a2);
students.add(a3);
// For Each to sweeping all objects inside of this ArrayList
for(Student student : students){
System.out.println(student.getName());
}
}
Enjoy!
I wanted to dynamically generate an array of fixed sized String[] (String[][] object), filled w. Strings of rows values from db to create JTable.
To do that, I used ArrayList of String[], dynamically filled it up. And then convert it to Array using list.toArray().
But .toArray() only convert the list into single dimension Array either Object[] or T[].
I need String[][] / Object[][] to use the JTable constructor.
The code
Object[][] dlist = (Object[][]) al.toArray();
generates: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;
ers = pdao.getEmployeeResultSet(prs.getInt("PROJ_ID"));
ArrayList<String[]> alist = new ArrayList<String[]>();
while (ers.next()){
String eid = ers.getString("EMP_ID");
String ename = ers.getString("EMP_NAME");
String gend = ers.getString("GENDER");
String bd = ers.getString("BIRTHDATE");
String addr = ers.getString("ADDRESS");
String city = ers.getString("City");
String[] str = {eid, ename, gend, bd, addr, city};
alist.add(str);
}
Object[][] dlist = (Object[][]) al.toArray();
String[] cnames = {"EMP_ID","EMP_NAME","GENDER","BIRTHDATE","Address","City"};
jtable = new JTable(dlist, cnames);
I used the tuturial on : http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SimpleTableDemoProject/src/components/SimpleTableDemo.java to create JTable.
Simply use
String[][] dlist = alist.toArray(new String[][]{});
The array you pass to the method can alternatively be used as the actual array that will be returned if you know the size (which you do with alist.size()), but it's really useful for the type of array that you want.
You can actually confirm this with
String[][] holder = new String[alist.size()][];
String[][] returned = alist.toArray(holder);
System.out.println(holder == returned);
will print
true
Now, obviously, since arrays are covariant, you can also do
Object[][] dlist = al.toArray(holder);
I would just create the double array myself, if you really wanted to:
public static String[][] getDArray(final ArrayList<String[]> aList) {
final int size = aList.size();
final String[][] ans = new String[size][];
for(int i = 0; i < size; ++i)
ans[i] = aList.get(i);
return ans;
}
Please help me to convert ArrayList to String[]. The ArrayList contains values of type Object(VO).
For example,
The problem is that I need to convert a country List to String Array, sort it and then put it in a list. However I am getting a ClassCastException.
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
I have assumed that your country List name is countryList.
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Please help me to convert ArrayList to String[], ArrayList Contains
Values Object(VO) as Values.
As you mentioned that list contains Values Object i.e. your own class you need toString() overridden to make this work correctly.
This code works. Assuming VO is your Value Object class.
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
The snippet of
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
will give you ArrayStoreException due VO is not the String type as required by native method arraycopy subsequently called from toArray one.
In case your ArrayList contains Strings, you can simply use the toArray method:
String[] array = list.toArray( new String[list.size()] );
If that is not the case (as your question is not completely clear on this), you will have to manually loop over all elements
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
What are we doing here:
String[] array is the String array you need to convert your
ArrayList to
list is your ArrayList of VO objects that you have in hand
List#toArray(String[] object) is the method to convert List objects
to Array objects
As correctly suggested by Viktor, I have edited my snippet.
The is a method in ArrayList(toArray) like:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
Then to sort you have::
Arrays.sort(countries);
Then re-converting to List like ::
List<String> countryList = Arrays.asList(countries);
Prior to Java 8 we have the option of iterating the list and populating the array, but with Java 8 we have the option of using stream as well. Check the following code:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);
I need to put several strings into a java array for example.
"Dog","Cat","Lion","Giraffe"
"Car","Truck","Boat","RV"
each of the above would be 1 key in the array
array[0] = "Dog","Cat","Lion","Giraffe"
array[1] = "Car","Truck","Boat","RV"
Not sure how to do this,or should I be using something other than an array,and how to get each individual element i.e array[0]"Lion"
Thanks
Declare the array like this:
String [][]array = {
{ "Dog","Cat","Lion","Giraffe"},
{"Car","Truck","Boat","RV"}
};
and use the items like this:
array[0][0]; // this would be "Dog"
array[1][0]; // this would be "Car"
You can use a multidimensional array:
String[][] something =
{
{ "hello", "kitties" },
{ "i", "am", "a", "pony" }
};
Well you can do it by declaring a map like so Map<String, MySweetObject> or create a List<String> and put each list into the array.
You need a jagged array, which is an array of arrays:
String [][]array = { {"Dog","Cat","Lion","Giraffe"}, {"Car","Truck","Boat","RV"}};
You can then access the content as this:
array[0] // will be the String array {"Dog","Cat","Lion","Giraffe"}
array[1] // will be the String array {"Car","Truck","Boat","RV"}
array[0][2] // Lion
array[1][0] // Car