Java控制台输出表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package cn.idea360.dubbo.consumer;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
* @author cuishiying
*/
@Builder
@Slf4j
public class ConsoleTable {

private List<String> headers;

private List<Map<String, Object>> rows;

public static void main(String[] args) throws Exception {
List<String> headers = Arrays.asList("id", "name");

Map<String, Object> data = new HashMap<>();
data.put("id", 1);
data.put("name", "admin");
List<Map<String, Object>> rows = Arrays.asList(data);

ConsoleTable.builder().headers(headers).rows(rows).build().print();
}

public void print() throws Exception {
new InnerPrint().print(headers, rows);
}

public static class InnerPrint {

private void print(List<String> headers, List<Map<String, Object>> rows) throws Exception {
// 获取列数
int columnSize = headers.size();
// 计算出每列最大长度
int[] columnMaxLengths = new int[columnSize];
// 结果集
List<Object[]> results = new ArrayList<>();
for (Map<String, Object> stringObjectMap : rows) {
// 保存当前行所有列
Object[] columnData = new Object[columnSize];
for (int i = 0; i < columnSize; i++) {
// 当前行数据按header排序
columnData[i] = stringObjectMap.get(headers.get(i));
// 计算当前列最大长度
columnMaxLengths[i] = calcColumnMaxLength(headers.get(i), columnData[i], columnMaxLengths[i]);
}
results.add(columnData);
}
printSeparator(columnMaxLengths);
printHeader(headers, columnMaxLengths);
printSeparator(columnMaxLengths);

// 数据table
for (Object[] row : results) {
for (int i = 0; i < columnSize; i++) {
System.out.printf("|%-" + columnMaxLengths[i] + "s", row[i]);
}
System.out.println("|");
}
printSeparator(columnMaxLengths);
}

public int calcColumnMaxLength(String header, Object data, int currentLength) {
int max = Math.max(header.length(), Objects.isNull(data) ? 0 : data.toString().length());
return Math.max(max, currentLength);
}

private void printHeader(List<String> headers, int[] columnMaxLengths) throws Exception {
for (int i = 0; i < headers.size(); i++) {
System.out.printf("|%-" + columnMaxLengths[i] + "s", headers.get(i));
}
System.out.println("|");
}

private void printSeparator(int[] columnMaxLengths) {
for (int columnMaxLength : columnMaxLengths) {
System.out.print("+");
for (int j = 0; j < columnMaxLength; j++) {
System.out.print("-");
}
}
System.out.println("+");
}

}

}