How to convert String to array<Float> in java

Viewed 44

Now I have a string like a vector :

String a = "[0.028997358,-0.259633,-0.10136852,0.2559176,-0.019660486,-0.57555103,0.17772871,0.2680008]";

How to turn it into List<Float> type?

Expected to get

List<Float> b = new ArrayList<Float>(Arrays.asList(0.028997358,-0.259633,-0.10136852,0.2559176,-0.019660486,-0.57555103,0.17772871,0.2680008));
2 Answers

Or small variation to previous answer:

Arrays.stream(a.replaceAll("[\\[\\]]", "").split(","))
                .map(Float::parseFloat)
                .collect(Collectors.toList());

You would be better off using a JSON parser but if you want to do it yourself then:

Arrays.stream(a.substring(1, a.length() - 1).split(",")).map(Float::parseFloat).collect(Collectors.toList())

Why would you rather do it with JSON parser if it's actually a JSON? Because a proper JSON parser takes into account all the whitespaces and everything else that this JSON might include. GSON is a viable option for example.

Also I wouldn't use Float in Java if it's not absolutely necessary as it's precision is not good. Use Double instead or if there might be huge number of digits and precision is important then consider using BigDecimal.

Related