You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从BeanItemContainer中获取指定property的唯一值列表

解决方案

直接从BeanItemContainer读取目标属性再去重是最适配需求的通用方案,不需要提前预处理数据源,可兼容不同Bean类的同属性ID场景。

通用实现代码

// 通用方法:从BeanItemContainer中获取指定property的唯一值集合
public Set<Object> getUniquePropertyValues(BeanItemContainer<?> container, String propertyId) {
    Set<Object> uniqueValues = new HashSet<>();
    // 遍历容器中所有BeanItem
    for (Object itemId : container.getItemIds()) {
        Object propertyValue = container.getItem(itemId).getItemProperty(propertyId).getValue();
        // 不需要null作为下拉选项可保留此行过滤,需要则删除
        if (propertyValue != null) {
            uniqueValues.add(propertyValue);
        }
    }
    return uniqueValues;
}

场景调用示例

针对你定义的Fun类,获取game属性唯一值、生成过滤器下拉选项的调用方式如下:

// 从已绑定数据的Grid中获取BeanItemContainer实例
BeanItemContainer<Fun> container = (BeanItemContainer<Fun>) grid.getContainerDataSource();
// 调用通用方法获取game属性的唯一值集合
Set<Object> uniqueGameValues = getUniquePropertyValues(container, "game");

// 生成过滤器下拉选项示例(以Vaadin ComboBox为例)
ComboBox gameFilter = new ComboBox("游戏筛选");
gameFilter.setItems(uniqueGameValues);
// 后续绑定过滤器逻辑即可

补充说明

  • 如果需要保持属性值的原始出现顺序,可以把实现中的HashSet替换为LinkedHashSet
  • 若要避免后续强转类型,可以使用泛型版的通用方法:
@SuppressWarnings("unchecked")
public <T> Set<T> getUniquePropertyValues(BeanItemContainer<?> container, String propertyId, Class<T> type) {
    Set<T> uniqueValues = new HashSet<>();
    for (Object itemId : container.getItemIds()) {
        Object value = container.getItem(itemId).getItemProperty(propertyId).getValue();
        if (type.isInstance(value)) {
            uniqueValues.add((T) value);
        }
    }
    return uniqueValues;
}
// 调用时可直接拿到指定类型的集合,无需强转
Set<String> uniqueGameValues = getUniquePropertyValues(container, "game", String.class);

内容的提问来源于stack exchange,提问作者Tony B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 14:45:03