Java: convert List to a String

前端 未结 22 2852
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  滥情空心
    2020-11-22 01:34

    A fun way to do it with pure JDK, in one duty line:

    String[] array = new String[] { "Bill", "Bob", "Steve","[Bill]","1,2,3","Apple ][" };
    String join = " and ";
    
    String joined = Arrays.toString(array).replaceAll(", ", join)
            .replaceAll("(^\\[)|(\\]$)", "");
    
    System.out.println(joined);
    

    Output:

    Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][


    A not too perfect & not too fun way!

    String[] array = new String[] { "7, 7, 7","Bill", "Bob", "Steve", "[Bill]",
            "1,2,3", "Apple ][" };
    String join = " and ";
    
    for (int i = 0; i < array.length; i++) array[i] = array[i].replaceAll(", ", "~,~");
    String joined = Arrays.toString(array).replaceAll(", ", join)
            .replaceAll("(^\\[)|(\\]$)", "").replaceAll("~,~", ", ");
    
    System.out.println(joined);
    

    Output:

    7, 7, 7 and Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][

提交回复
热议问题