convert two-dimensional array to string

前端 未结 4 1563
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 09:38

I\'m trying to convert a String[][] to a string for display in a GUI. Here\'s my code:

String[][] tableBornes = SearchPropertiesPlugin.FillBorne         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 10:02

    If you want to create one-line representation of array you can use Arrays.deepToString.


    In case you want to create multi-line representation you will probably need to iterate over all rows and append result of Array.toString(array[row]) like

    String[][] array = { { "a", "b" }, { "c" } };
    
    String lineSeparator = System.lineSeparator();
    StringBuilder sb = new StringBuilder();
    
    for (String[] row : array) {
        sb.append(Arrays.toString(row))
          .append(lineSeparator);
    }
    
    String result = sb.toString();
    

    Since Java 8 you can even use StringJoiner with will automatically add delimiter for you:

    StringJoiner sj = new StringJoiner(System.lineSeparator());
    for (String[] row : array) {
        sj.add(Arrays.toString(row));
    }
    String result = sj.toString();
    

    or using streams

    String result = Arrays
            .stream(array)
            .map(Arrays::toString) 
            .collect(Collectors.joining(System.lineSeparator()));
    

提交回复
热议问题