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);
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103

2 Answers2

1

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]
WJS
  • 36,363
  • 4
  • 24
  • 39
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();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    If possible, in all new answers, please include a note about [`Stream::toList`](https://stackoverflow.com/q/65969919/10819573) available since Java-16. – Arvind Kumar Avinash Apr 12 '21 at 21:39