Sunday, 5 January 2020

How to convert char[] to List in Java?

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

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

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

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

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

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

  }
  return result;
 }

 public static void main(String args[]) throws IOException {
  char[] arr = { 'a', 'e', 'i', 'o', 'u' };

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

 }
}


Output
a e i o u    


You may like

No comments:

Post a Comment