Java中使用HashMap设置带跨列的不规则表格表头
实现带Col-Span的不规则表头方案
你之前用的HashMap只能存平级键值对,没法表达表头的层级关系和合并列(colspan)属性,所以咱们换用自定义表头类+树形结构来实现需求:
1. 定义表头实体类
先写一个TableHeader类,用来封装表头的显示文本、跨列数和子表头列表:
import java.util.List; public class TableHeader { private String name; // 表头显示文字 private int colspan; // 跨列数,默认是1 private List<TableHeader> children; // 子表头集合 // 普通子表头的构造方法 public TableHeader(String name) { this(name, 1, null); } // 带跨列和子表头的主表头构造方法 public TableHeader(String name, int colspan, List<TableHeader> children) { this.name = name; this.colspan = colspan; this.children = children; } // 按需生成Getter方法(简化展示) public String getName() { return name; } public int getColspan() { return colspan; } public List<TableHeader> getChildren() { return children; } }
2. 构建层级表头结构
用上面的类搭建你需要的双层表头:
import java.util.Arrays; public class TableDemo { public static void main(String[] args) { // 创建下层子表头 TableHeader fromCountry = new TableHeader("From Country"); TableHeader fromCity = new TableHeader("From City"); TableHeader toCountry = new TableHeader("To Country"); TableHeader toCity = new TableHeader("To City"); // 创建上层主表头,设置colspan=2并关联对应的子表头 TableHeader fromPlace = new TableHeader("From Place", 2, Arrays.asList(fromCountry, fromCity)); TableHeader toPlace = new TableHeader("To Place", 2, Arrays.asList(toCountry, toCity)); // 最终的顶层表头列表 List<TableHeader> rootHeaders = Arrays.asList(fromPlace, toPlace); } }
3. 渲染时处理Col-Span
不管是输出到HTML还是控制台,都可以通过遍历这个树形结构,给主表头加上合并逻辑。比如生成HTML表头的示例:
// 示例:生成符合要求的HTML表头 public static void renderHtmlHeaders(List<TableHeader> headers) { // 渲染顶层主表头 System.out.println("<tr>"); for (TableHeader header : headers) { System.out.printf("<th colspan='%d'>%s</th>", header.getColspan(), header.getName()); } System.out.println("</tr>"); // 渲染下层子表头(如果是多层表头,这里改成递归遍历即可) System.out.println("<tr>"); for (TableHeader header : headers) { if (header.getChildren() != null) { for (TableHeader child : header.getChildren()) { System.out.printf("<th>%s</th>", child.getName()); } } else { System.out.printf("<th>%s</th>", header.getName()); } } System.out.println("</tr>"); }
调用后会输出:
<tr> <th colspan='2'>From Place</th> <th colspan='2'>To Place</th> </tr> <tr> <th>From Country</th> <th>From City</th> <th>To Country</th> <th>To City</th> </tr>
如果是控制台输出,只需要根据colspan值调整主表头的显示宽度就行,核心逻辑都是基于这个层级结构来遍历处理。
内容的提问来源于stack exchange,提问作者Arslan Ilyas
相关产品推荐
相关产品推荐

