有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

映射中数组列表中的java设置值

我正在从elasticsearch获取记录,并试图以列表的形式返回。但是我从sourceAsMap添加到列表时出错

请在下面找到我的代码

SearchHit[] searchHits = searchResponse.getHits().getHits();
    List<Product> productList=new ArrayList<Product>();
    for (SearchHit hit : searchHits) {
        // get each hit as a Map

        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        product=new Product();
        product.setName(sourceAsMap.get("name").toString());
        productList.add(product.setName(sourceAsMap.get("name").toString()));  // throwing error in this line

    }

    return productList;
}   

请找到我的POJO课程:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {

    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

共 (1) 个答案

  1. # 1 楼答案

    我相信你得到了The method add(void) is undefined for the type Product。你的Product#setName方法返回类型是void,所以你实际上是在尝试将void添加到ProductList。你应该做productList.add(product)而不是productList.add(product.setName(sourceAsMap.get("name").toString()));

    您的代码应该如下所示:

        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        product=new Product();
        product.setName(sourceAsMap.get("name").toString());
        productList.add(product);