简体   繁体   中英

How to print a ArrayList of String arrays in java which is a value of Map

I want to print the content of this attribute:

private HashMap<RegionVersObj,  ArrayList<String[]>> region;

I have done this with the below code. Inside the toString( ) method I am iterating with the Map Entry. I have created a StringBuffer object and appending the content in it.

 public String toString() {     
        StringBuffer regionToPrint = new StringBuffer();
          for (Map.Entry<RegionVersObj,  ArrayList<String[]>> entry : region.entrySet())
            {
              regionToPrint.append(entry.getKey().toString());
              regionToPrint.append("=[");
              for(String[] s:entry.getValue()){
                  regionToPrint.append("[");
                  for(String s1:s){
                      regionToPrint.append(s1);
                      regionToPrint.append(",");
                  }
                  regionToPrint.append("],");
              }
        }

        return "region=" + regionToPrint.toString();
    }

This is the way I am trying to solving this. But I want to know is there any better way in which I can solve this?

Kindly use the JAVA 1.8. Since it has the more in build functions. Example we can make the String[] array into comma separated values using String.join()

 region.forEach((k,v)->{
              regionToPrint.append(k.toString());
              regionToPrint.append("=[");
              for(String[] s:v){
                  regionToPrint.append("[");
                  regionToPrint.append(String.join(",", s));
                  regionToPrint.append("],");
              }
              regionToPrint.append("],");
        }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM