Saturday 15 February 2020

Java: Convert Object array to String array

By traversing to each element of array and copy the content of toString() method.
public static String[] getStringArray(Object[] objects) {
 if (objects == null || objects.length == 0) {
  return null;
 }

 String[] result = new String[objects.length];

 int counter = -1;
 for (Object obj : objects) {
  counter++;

  if (obj == null) {
   result[counter] = null;
  } else {
   result[counter] = obj.toString();
  }
 }

 return result;
}

Find the below working application.

Employee.java
package com.sample.app;

public class Employee {

 private int id;
 private String name;

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append(id).append(":").append(name);
  return builder.toString();
 }

}

App.java
package com.sample.app;

public class App {

 private static void printArray(String[] arr) {
  if (arr == null || arr.length == 0) {
   return;
  }

  for (String s : arr) {
   System.out.print(s + "  ");
  }
  System.out.println();
 }

 public static String[] getStringArray(Object[] objects) {
  if (objects == null || objects.length == 0) {
   return null;
  }

  String[] result = new String[objects.length];

  int counter = -1;
  for (Object obj : objects) {
   counter++;

   if (obj == null) {
    result[counter] = null;
   } else {
    result[counter] = obj.toString();
   }
  }

  return result;
 }

 public static void main(String[] args) {
  Employee[] emps = { new Employee(1, "Ram"), new Employee(2, "Joel"), new Employee(3, "Bomma") };

  String[] result1 = getStringArray(emps);

  printArray(result1);

 }

}

Output
1:Ram  2:Joel  3:Bomma 


You may like

No comments:

Post a Comment