映射中数组列表中的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 楼答案
我相信你得到了
The method add(void) is undefined for the type Product
。你的Product#setName
方法返回类型是void
,所以你实际上是在尝试将void
添加到Product
的List
。你应该做productList.add(product)
而不是productList.add(product.setName(sourceAsMap.get("name").toString()));
您的代码应该如下所示: