如何获取PrimeFaces DataTable行组详情并在后台Bean中输出
获取PrimeFaces DataTable行组信息及行索引的方法
PrimeFaces的DataTable组件并未直接提供获取行组详情的API,你可以通过以下两种方式实现需求:
方法1:从DataTable的显示数据中提取行组
该方法适用于需要获取当前页面已过滤/排序后的数据分组情况,直接利用绑定的DataTable对象获取展示数据:
public void printRowGroups() { // 获取DataTable当前展示的过滤/排序后的数据列表 List<你的实体类> displayedItems = (List<你的实体类>) dtPartidasSelec.getWrappedData(); if (displayedItems == null || displayedItems.isEmpty()) { System.out.println("无数据可分组"); return; } String currentGroup = displayedItems.get(0).getDesGrupo(); List<Integer> rowIndices = new ArrayList<>(); // 遍历数据,按分组聚合行索引 for (int i = 0; i < displayedItems.size(); i++) { 你的实体类 item = displayedItems.get(i); if (!item.getDesGrupo().equals(currentGroup)) { // 打印上一个分组信息 System.out.println("分组名称:" + currentGroup); System.out.println("包含的行索引(页面显示序号):" + rowIndices); // 重置分组状态 currentGroup = item.getDesGrupo(); rowIndices = new ArrayList<>(); } rowIndices.add(i + 1); // 对应页面中显示的行号(index+1) } // 打印最后一个分组 System.out.println("分组名称:" + currentGroup); System.out.println("包含的行索引(页面显示序号):" + rowIndices); }
方法2:提前在后台Bean中预分组数据
如果不需要考虑实时过滤/排序的影响,可以在加载数据时直接将数据按分组字段聚合,后续直接使用预分组结果:
// 定义分组存储结构 private Map<String, List<你的实体类>> groupedPartidas; // 加载数据时同步分组 public void loadData() { lstPartidasSelec = // 从数据源获取原始数据列表 // 按desGrupo字段分组 groupedPartidas = lstPartidasSelec.stream() .collect(Collectors.groupingBy(你的实体类::getDesGrupo)); } // 打印分组信息 public void printRowGroups() { for (Map.Entry<String, List<你的实体类>> entry : groupedPartidas.entrySet()) { String groupName = entry.getKey(); List<你的实体类> groupItems = entry.getValue(); // 获取原始列表中的行索引(对应页面indexOf+1的逻辑) List<Integer> originalIndices = groupItems.stream() .map(item -> lstPartidasSelec.indexOf(item) + 1) .collect(Collectors.toList()); System.out.println("分组名称:" + groupName); System.out.println("包含的原始行索引:" + originalIndices); } }
注意事项
- 若使用方法1,
rowIndices为页面显示的行号;若使用方法2,originalIndices为原始数据列表中的位置(需确保实体类对象唯一,否则indexOf会返回第一个匹配项)。 - 若DataTable开启了分页,需注意
getWrappedData()仅返回当前页的数据。
内容的提问来源于stack exchange,提问作者Edgard Moreno
相关产品推荐
相关产品推荐

