Difference between String and String[] - java

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

Related

Unlikely argument type String for contains(Object) on a Collection<String[]>

I'm getting the warning in Eclipse:
Unlikely argument type String for contains(Object) on a Collection<String[]>
Is there a way to modify the code so as to not get this warning?
String[] findNames = {"shares","ticker","avgCost","mktPrice","gnLs","totVal"};
ArrayList<String[]> publicNames = new ArrayList<String[]>();
for(Field publicField : publicFields) {
String[] name = new String[2];
name[0] = publicField.getName();
name[1] = publicField.getType().toString();
publicNames.add(name);
}
for (int i = 0; i < 6; i++) {
if(publicNames.contains(findNames[i])) {
System.out.println("\n***** Warning: instance variable "
+ findNames[i]
+ " declared as \"public\" *****\n ");
}
}
It's because publicNames is an ArrayList of string[] and you're trying to see if it contains a single string, which is not applicable.
Now I don't know why you are storing tuples of strings and then types. I'd advise you to change this way, but if you really need them, you might want to look at #Deadpool's answer
ArrayList<String> publicNames = new ArrayList<String>();
Now this line won't throw any warning
publicNames.contains(findNames[i])
You are trying to compare String with String array, If you want to find String value contains in list of String array, List<String[]>
You can do this by using java-8 streams
publicNames.stream().flatMap(Arrays::stream).anyMatch(item->item.equals(findNames[i]))
will return true if any of String[] in publicNames contains findNames[i], or will return false

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

Convert a List of objects to a String array

I have the below pojo which consists of the below members so below is the pojo with few members in it
public class TnvoicetNotify {
private List<TvNotifyContact> toMap = new ArrayList<TvNotifyContact>();
private List<TvNotifyContact> ccMap = new ArrayList<TvNotifyContact>();
}
now in some other class i am getting the object of above class TnvoicetNotify in a method signature as parameter as shown below .. So i want to write the code of extraction from list and storing them in string array within this method itself
public void InvPostPayNotification(TnvoicetNotify TnvoicetNotify)
{
String[] mailTo = it should contain all the contents of list named toMap
String[] mailCC = it should contain all the contents of list named ccMap
}
now in the above class i need to extract the toMap which is of type list in the above pojo named TnvoicetNotify and i want to store each item if arraylist in a string array as shown in below fashion
for example first item in list is A1 and second is A2 and third is A3
so it should be stored in string array as
String[] mailTo = {"A1","A2","A3"};
similarly i want to achieve the same for cc section also as in above pojo it is in list i want to store in the below fashion
String[] mailCc = {"C1","C2","C3"};
so pls advise how to achieve this within InvPostPayNotification method
Pseudo code, because I don't know details for TnvoicetNotify:
public void invPostPayNotification(final TnvoicetNotify tnvoicetNotify)
{
final List<String> mailToList = new ArrayList<>();
for (final TvNotifyContact tv : tnvoicetNotify.getToMap()) { // To replace: getToMap()
mailToList.add(tv.getEmail()); // To replace: getEmail()
}
final String[] mailTo = mailToList.toArray(new String[mailToList.size()])
// same for mailCc then use both arrays
}
If you are using Java 8, you could simply use a one liner :
String[] mailCC = ccMap.stream().map(TvNotifyContact::getEmail).toArray(String[]::new);

Convert a String into an array List Java

I have a String like this:
["http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"]
How can I convert it into an ArrayList of Strings?
Use Arrays#asList
String[] stringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> stringList = Arrays.asList(stringArray);
In case your string contains braces [] and double quotes "", then you should parse the string manually first.
String yourString = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\", \"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
String[] stringArray = yourString
.substring(1, yourString.length() - 2)
.replace('"', '\0')
.split(",\\s+");
List<String> stringList = Arrays.asList(stringArray);
Try the above if and only if you will always receive your String in this format. Otherwise, use a proper JSON parser library like Jackson.
This would be more appropriate
String jsonArr = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\",
\"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
List<String> listFromJsonArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonArr);
for(int i =0 ;i<jsonArray.length();i++){
listFromJsonArray.add(jsonArray.get(i).toString());
}
And don't forget to add json library
You can use simple CSV parser if you remove the first and last brackets ('[',']')
Something like this:
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
Method 1: Iterate through the array and put each element to arrayList on every iteration.
Method 2: Use asList() method
Example1:
Using asList() method
String[] urStringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> newList = Arrays.asList(urStringArray);
Example2
Using simple iteration
List<String> newList = new ArrayList<String>();
for(String aString:urStringArray){
newList.add(aString);
}

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

Categories