简体   繁体   中英

How to format array in string

I want to format log like this:

"order with orderid=1,orderid=2,orderid=3,orderid=4"

I have array with values [1,2,3,4] . I understand that it is enough easy to use loop for this but I want to know if there is tool in jdk (or library) which can do this.

Using java 8:

int[] n = new int[]{1,2,3,4};
String orders = Arrays.stream(n).mapToObj(i -> "orderid=" + i).collect(Collectors.joining(","));
String result = "order with " + orders;

You can easily build such a String using for-loop :

for (int i = 0; i < array.length; i++) {
    //String append with orderid and array[i];
}

You can achieve this as below way,

    public static void main (String[] args) throws java.lang.Exception
    {
       String strData[] = {"1","2","3"};
       String result = Arrays.toString(strData); // OutPut [1,2,3]

       result = result.substring(1, result.length() - 1); // OutPut 1,2,3
       result = result.replaceAll(",", ", OrderId=");

       System.out.println("Order with OrderId=" + result);
       //OutPut Order with OrderId=1, OrderId=2
    }

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