Saturday 4 January 2020

How to convert float[] to List in Java?

By traversing to the elements of array you can convert float[] to List<Float>.
public static List<Float> getBoxedList(float[] arr) {
 if (arr == null)
  return null;

 List<Float> result = new ArrayList<>();

 for (float i : arr) {
  result.add(i);

 }
 return result;
}

App.java
package com.sample.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class App {

 private static void printElements(List<Float> arr) {
  for (float i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static List<Float> getBoxedList(float[] arr) {
  if (arr == null)
   return null;

  List<Float> result = new ArrayList<>();

  for (float i : arr) {
   result.add(i);

  }
  return result;
 }

 public static void main(String args[]) throws IOException {
  float[] arr = { 1.1f, 3.3f, 5.5f, 7, 2, 4, 6, 8, 10 };

  List<Float> result1 = getBoxedList(arr);
  printElements(result1);

 }
}

Output
1.1 3.3 5.5 7.0 2.0 4.0 6.0 8.0 10.0    

You may like

No comments:

Post a Comment