Sunday 5 January 2020

How to convert boolean[] to List in Java?


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

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

 for (boolean 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<Boolean> arr) {
  for (boolean i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

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

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

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

  }
  return result;
 }

 public static void main(String args[]) throws IOException {
  boolean[] arr = { true, false, true, false };

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

 }
}

Output
true false true false



You may like

No comments:

Post a Comment