-4

Entity MyObject has the following properties:

private String tblName;
private String colName;
private String dataType;

I have a list of those: List<MyObject>. Now I need to convert this List to a singular String for debugging purposes, e.g.:

Object 1: (dataType=test, colName=test2, dataType=int), Object 2..."

What is the best way to do this?

Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
  • 5
    It's ununderstandable what you're asking here. – Maroun Mar 19 '15 at 08:26
  • possible duplicate of [Best way to convert an ArrayList to a string](http://stackoverflow.com/questions/599161/best-way-to-convert-an-arraylist-to-a-string) – runDOSrun Mar 19 '15 at 08:28
  • 1
    You can override the toString method on MyObject and return the `(dataType=test, colName=test2, dataType=int)` for the array list you will need to iterate the collection and call `myObject.toString` – Kenneth Clark Mar 19 '15 at 08:57
  • This question is definitely not too break any more. Those that have down-voted, please reconsider in order to allow for the answering process to unfold and make the internet a better place. – Fritz Duchardt Mar 19 '15 at 13:36

1 Answers1

1

You can override the toString method on your MyObject like below

 public class MyObject
 {
   private String tblName;
   private String colName;
   private String dataType;

   public String getTblName()
   {
     return tblName;
   }

   public void setTblName(String tblName)
   {
     this.tblName = tblName;
   }

   public String getColName()
   {
     return colName;
   }

   public void setColName(String colName)
   {
     this.colName = colName;
   }

   public String getDataType()
   {
     return dataType;
   }

   public void setDataType(String dataType)
   {
     this.dataType = dataType;
   }

   public String toString()
   {
     return String.format("(tblName=%s, colName=%s, dataType=%s)", tblName, colName, dataType);
   }
 }

For your ArrayList you will need to iterate the list and build your results

   public static void main(String[] args)
   {
     ArrayList<MyObject> objectList = new ArrayList<MyObject>();
     MyObject obj1 = new MyObject();
     obj1.setColName("Col1");
     obj1.setTblName("Tab1");
     obj1.setDataType("data1");

     MyObject obj2 = new MyObject();
     obj2.setColName("Col1");
     obj2.setTblName("Tab1");
     obj2.setDataType("data1");

     objectList.add(obj1);
     objectList.add(obj2);

     StringBuilder stringBuilder = new StringBuilder();

     int count = 1;
     for (MyObject myObject : objectList)
     {
       stringBuilder.append(String.format("Object %d %s ", count, myObject.toString()));
       count++;
     }
     System.out.println(stringBuilder.toString());
   }
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26