0

Good afternoon, Community!

I have a List:

List<String> rate = new ArrayList<>(); 

and I need to convert the data into a float if it can be done with java 8 stream. I was doing it in the following way:

float valueRate = Float.parseFloat(rate);
2
  • List rate = new ArrayList <> (); - float valueRate = Float.parseFloat (rate); Commented Apr 12, 2021 at 21:19
  • Please read How to ask and update your question. Commented Apr 16, 2021 at 5:51

2 Answers 2

2

Try it like this:

  • Given a list of strings floating point values.
  • map them to a stream of float using Float.valueOf()
  • and collect into a List.
List<String> list = List.of("1.2", "3.4", "2.5f");
List<Float> floats = list.stream().map(Float::valueOf).collect(Collectors.toList());
    
System.out.println(floats);

Prints

[1.2, 3.4, 2.5]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Stream#map with Float.valueOf (to avoid autoboxing).

List<Float> res = rate.stream().map(Float::valueOf).collect(Collectors.toList());

With Java 16:

List<Float> res = rate.stream().map(Float::valueOf).toList();

1 Comment

If possible, in all new answers, please include a note about Stream::toList available since Java-16.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.