简体   繁体   中英

Convert a List String to an ArrayList Float with Stream in java 8

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

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM