Converting ArrayList<String[]> to String[][] or Object[][] - java

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

Related

How to get value from List<String[]>

I'm successfully getting the values from CSV file in to List<String[]>, but having problem in moving values from List<String[]> to String[] or to get single value from List. I want to copy these values in to string array to perform some functions on it.
My values are in scoreList
final List<String[]> scoreList = csvFile.read();
Now I want to get single value from this scoreList. I have tried this approaches but could not get the value
String[] value=scoreList.get(1);
You want a single value but you are declearing an array an you are tring to assign string to string array. If you want a single value, try this;
String x = scoreList.get(1);
or
if you want to convert listarray to string array try this;
String[] myArray = new String[scoreList.size()];
for(int i=0; i<scoreList.size();i++)
{
myArray[i]=scoreList.get(i);
}
Suppose you want to collect values of the 2nd column (index 1) then you can try this
// Collect values to this list.
List<String> scores = new ArrayList<String>();
final List<String[]> scoreList = csvFile.read();
// For each row in the csv file
for (String [] scoreRow : scoreList ) {
// var added here for readability. Get second column value
String value = scoreRow[1];
scores.add(value);
}

Error on Convert ArrayList to Arrays PayPalItem

I need a Array to PayPal Items must however go another arraylist to add the items as I do that?
ArrayList<PayPalItem[]> stringArrayList = new ArrayList<PayPalItem[]>();
for (int i=0; i<resultado.size(); i++) {
PayPalItem[] items;
double x = Math.round(((resultado.get(i).getTotal() / resultado.get(i).getPreco())));
int quantidade = (int) x;
String preco = String.format("%.2f", resultado.get(i).getPreco());
String nome = resultado.get(i).getProduto();
items = new PayPalItem[]{
new PayPalItem(nome, quantidade, new BigDecimal(resultado.get(i).getPreco()), "BRL",
"dinner")
};
stringArrayList.add(items); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);
I'm trying to convert an ArrayList to the Array however I get this error
Conversion from an arrayList i.e. ArrayList<Something> list to an Array is done this way (as you already did):
list.toArray(Something[]) <- notice that the parameter here is an array of Something elements.
so in your case: Something is PayPalItem[] then you need to add an extra [] because you have an array of arrays.
replacing your last two lines of your code by these two will solve your issue.
PayPalItem[][] items = new PayPalItem[stringArrayList.size()][];
//if you want your array
PayPalItem[][] stringArray = stringArrayList.toArray(items);
but anyway, I cannot understand why do you need an array of arrays instead of simply just a list or an array. I mean something like this:
ArrayList<PayPalItem> stringArrayList = new ArrayList<PayPalItem>();
for (int i = 0; i < 2; i++) {
//create the PayPalItem and add to the list
stringArrayList.add(new PayPalItem()); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);

Remove duplicates form arraystring

I have filled in an ArrayList of strings with suppliernumbers. This list contains duplicates values so I want to delete them with the HashSet.
I get following error: Invalid expression as statement
On line => Set set = new HashSet(leveranciers); (Set underlined)
Any idea why?
String[] leveranciers = new String[wdContext.nodeShoppingCart().size()];
for(int i = 0; i<wdContext.nodeShoppingCart().size(); i++){
String productnumber = wdContext.nodeShoppingCart().getShoppingCartElementAt(i).getMatnr()
wdThis.wdGetAchatsIndirectController().GetDetails(productnumber, "NL");
leveranciers[i] = wdContext.currentEt_DetailsElement().getLifnr();
}
//Remove duplicates from array
Set<String> set = new HashSet<String>(leveranciers);
set.toArray(new String[0]);
for(int y = 0; y<set.size();y++){
PdfPTable table = GetTable(set[y]);
byte[] pdf = wdThis.wdGetAchatsIndirectController().GetPDFFromFolder("/intranetdocuments/docs/AchatsIndirect", table);
wdThis.wdGetAchatsIndirectController().PrintPDF(pdf);
}
HashSet doesn't have a constructor which accepts an array.
Have a look at HashSet documentation.
http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
You can achieve your goal by using Arrays.asList method like that:
final String[] strings = new String[] {"ab", "ba", "ab"};
final Set<String> set = new HashSet<String>(Arrays.asList(strings));

How to convert an ArrayList<T> to Object[][] in Java?

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.

How to convert ArrayList to String[] in java, Arraylist contains VO objects

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

Categories