How to get value from List<String[]> - java

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

Related

How to store all ArrayList<ArrayList<String>> values into ArrayList<String>?

I am having issue to store all values of ArrayList<ArrayList<String>> into ArrayList<String>. Here stylistIDArray and durationArray are array of array. I want to store all their values in stylistId and duration respectively. The stylistid and duration are array of string.
Here's my attempt, but it stores only the last item of each array of array.
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId = new ArrayList<>();
ArrayList<String>duration = new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId = stylistIDArray.get(i);
duration = durationArray.get(i);
}
Note : I have already tried this, but doesn't work for me.
To be generic, First let be an list of list of objects
List<List<Object>> listOfList;
That you want to put into a list of object
List<Object> result;
Note the result list will contain every object contain is the input list. This transformation will loose the information of which object was in which list.
You have to loop through the listOfList. At each loop you obtain a list of object (List<Object> listOfObject). Then loop through these lists to obtain every object (Object o). Then add these object to the result list (result.add(o)).
for(List<Object> listOfObject : listOfList) {
for(Object o : listOfObject) {
result.add(o);
}
}
In your case, the problem is that you use affectation instead of add(). At every loop this replaces the value by the new one. So at the end you have stored only the last item of each list.
stylistId=stylistIDArray.get(i); //This replace the existing stylistId
Instead try something like
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String> stylistId = new ArrayList<>();
ArrayList<String> duration = new ArrayList<>();
for(ArrayList<String> l : stylistIDArray) {
for(String s : l) {
stylistId.add(s);
}
}
for(ArrayList<String> l : durationArray ) {
for(String s : l) {
duration.add(s);
}
}
You doing wrong operation with arraylist, in loop you are getting data from stylistIDArray and assign to aryalist, not inserting in list, have look this
stylistIDArray=differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray=differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId=new ArrayList<>();
ArrayList<String>duration=new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId.add(stylistIDArray.get(i));
duration.add(durationArray.get(i));
}
Hope it will help you!

Difference between String and String[]

I am trying to add the strings to a csv file in Android. As per the syntax it is asking to add String [] but I have added below line
String [] s1;
s1=c2.getString(c2.getColumnIndex("Sname"));
retrieving the value from cursot and storing it in s1. Above line giving me the error:
Type mismatch: cannot convert from String to String[]
What is the difference between String and String[], and how can I convert to String[]?
I am a beginner to Android and Java.
Edit
I was able to store but unable to store in writeline of csv class.
CSVWriter export=new CSVWriter(new FileWriter("/sdcard/"+stock+".csv"));
export.writeAll(s1, true);
error:
The method writeAll(List<String[]>, boolean) in the type
CSVWriter is not applicable for the arguments (String[], boolean)
String is a single String object String[] is an array of String objects. The problem is you are trying to add a String Object to a String array without specifying an index.
You could do something like:
String [] s1 = new String[1];
s1[0]=c2.getString(c2.getColumnIndex("Sname"));
Just an example or you could just create a String Object instead of a String array:
String s1;
s1=c2.getString(c2.getColumnIndex("Sname"));
Basically if you want to use an array you must specify an index of that array to Store the object because there are multiple objects stored in the array each one has its own index.
Try doing this:
ArrayList<String[]> csvExport = new ArrayList<String[]>();
csvExport.add(s1);
CSVWriter export=new CSVWriter(new FileWriter("/sdcard/"+stock+".csv"));
export.writeAll(csvExport, true);
This will only add one line to your csv file. If you want multiple lines you will need to create multiple String[] and add each String[] to your ArrayList csvExport.
Think of a String[] array as your columns for example:
String[] columnNames = new String[2];
columnNames[0] = "ID";
columnNames[1] = "Name";
String[] person1 = new String[2];
person1[0] = "1";
person1[1] = "George";
ArrayList<String[]> csvExport = new ArrayList<String[]>();
csvExport.add(columnNames);
csvExport.add(person1);
CSVWriter export=new CSVWriter(new FileWriter("/sdcard/"+stock+".csv"));
export.writeAll(csvExport, true);
The code above would give you a csv file like this:
ID Name
1 George
You are trying to assign a String to an array of String objects, which will not work. You can declare a String like so:
String str = c1.getString(c2.getColumnIndex("Sname"));
Or you can assign the String to an index in the array of String objects like so, and this will work, but I don't see a reason to use an array here.
String [] strArray = new String[5]; // String array of length 5
strArray[0] = c1.getString(c2.getColumnIndex("Sname")); // set the first element in the array to reference a String object

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

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

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