【问题标题】:Java get specific value from list and add to other listJava 从列表中获取特定值并添加到其他列表
【发布时间】:2017-08-25 03:10:37
【问题描述】:

我想问一些问题,如何从列表中获取特定值并添加到另一个列表,假设我有列表(这是来自 hibernate DAO 的 cust 列表),例如:

[["marketplace","001-002-003"],["insurance","142-523-132"],["car purchase","982349824"]]

我只想从该列表中获取“marketplace”、“insurance”和“car purchase”的值并添加到名为“bu”的新列表中

这是我的代码

public @ResponseBody String findBU(@RequestBody AllCustomerHist customer){
        BigDecimal id= customer.getId();
        String message;
        List<String> bu= new ArrayList<>();
        int i;

        System.out.println("ID = "+id);
        List<AllCustomerHist> cust = allCustomerHistService.findBU(id);


        for (i=0; i<cust.size(); i++){
            System.out.println("iteration = "+i);

            // stumbled here //
        }

        JSONObject json = new JSONObject();
        json.put("id", id);
        json.put("BU", bu);

        message = json.toString();
        return message;

    }

这是我的 AllCustomerHistDaoImpl 类

//release 1.3
@SuppressWarnings("unchecked")
public List<AllCustomerHist> findBU(BigDecimal adpId) {
    // TODO cek kodingan
    Criteria criteria = getSession().createCriteria(AllCustomerHist.class)
            .setProjection(Projections.projectionList()
                    .add(Projections.property("srctable"), "srctable")
                    .add(Projections.property("customerId"), "customerId"))
    .add(Restrictions.eq("adpId", adpId));

    return (List<AllCustomerHist>)criteria.list();
}

注意AllCustomerHist是一个实体类,用于在hibernate中定义表

感谢您的帮助:D

【问题讨论】:

  • AllCustomerHist的结构是什么?更重要的是,为什么假设我们会知道?
  • 为什么使用 ID 作为 BigDecimal?
  • 您已经以一种看起来像地图的方式显示了来自 Hibernate 的客户列表。然后,您将使用带有 AllCustomerHist 类型元素的列表。好像不兼容。
  • @PauloPedroso cust 的结果不是一对 key:value,它的结果集来自 2 列,首先是 srctable 列(“市场、保险、购车”来自这里)和第二个来自 customerID 列
  • @galih 也许你应该发布 AllCustomerHist 代码。

标签: java spring list hibernate rest


【解决方案1】:

由于您需要进行一些验证,并且您需要删除整个 AllCustomerHistobject 我要做的是以下代码

List<AllCustomerHist> cust = allCustomerHistService.findBU(id);
List<String> bu = new ArrayList<String>(cust.size());

        for (i=0; i<cust.size(); i++){
            System.out.println("iteration = "+i);
            AllCustomerHist aCust = cust.get(i);
            bu.add(aCust.getSrctable());

        }
//here your bu list should be ready to be used.....

我希望这是你需要的

【讨论】:

  • 它不能从对象转换为 allcustomerhist,您的代码是正确的,但我需要使用 setResultTransformer(Transformers.aliasToBean(AllCustomerHis‌​t.class)) 转换我的结果集
  • 啊,所以AllCustomerHist 不是实体类...。我知道它是实体类,否则我会告诉你使用休眠转换器。无论如何,我很高兴它有效
【解决方案2】:

如果你使用JDK1.8+,也可以这样:

List<AllCustomerHist> cust = allCustomerHistService.findBU(id);
List<String> bu = cust.stream()
    .map(AllCustomerHist::getSrctable)
    .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2023-04-01
    • 1970-01-01
    • 2020-07-06
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多