Reputation: 3137
I have to retrieve some data from a file to show it in a chart. The function that shows the chart requires he data as float[]
whereas the retrieved data is in the form ArrayList<String>
.
What is the easiest way to convert ArrayList<String>
to float[]
?
try {
FileInputStream fIn = context.openFileInput(fileDir+fileName);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
ArrayList<String> list_prix = new ArrayList<String>();
String ligne;
while ((ligne = b.readLine()) != null) {
String dtVal = ligne.split(" ")[2];
dtVal = dtVal.substring(0, dtVal.length() - 2);
list_prix.add(dtVal);
}
//just here if i can convert list_prix to float[]
fIn.close();
ipsr.close();
}
catch (Exception e)
{
Log.e("blah", "Exception", e);
}
Thank you for your help.
Upvotes: 0
Views: 3583
Reputation: 2110
You can loop and use Float.parseFloat().
float [] floatValues = new float[list_prix.size()];
for (int i = 0; i < list_prix.size(); i++) {
floatValues[i] = Float.parseFloat(list_prix.get(i));
}
Now, this assumes that every string in your ArrayList can actually be parsed into a float. If not, it could throw an exception, so you may want to do this in a try/catch block if you are not sure.
Upvotes: 2
Reputation: 53516
I think the following will do it using Guava...
Collection<Float> floats = Collections2.transform(list_prix, new Function<String, Float>() {
public Float apply(String input) {
return Float.parseFloat(input);
}
});
Float[] floatArray = new Float[floats.size()];
floats.toArray(floatArray);
Upvotes: 3