我有一个 HashMap
,我想将其转换为自定义对象 Response
。我不确定如何将 HashMap
中的值(80、190、900、95)设置为自定义对象?如何在 Response 对象中编写一个单独的函数来设置价格字段或将两个参数(键和值)设置为 fromString
函数。
class Converter{
public static void main(String[] args) {
Map<String, Long> map = new HashMap<String, Long>();
map.put("111", 80) // first
map.put("1A9-ppp", 190) // second
map.put("98U-6765", 900) // third
map.put("999-aa", 95) // fourth
List<Response> list =
map.keySet().stream().map(ent-> Response.fromString(ent.getKey(), ent.getValue())).collect(Collectors.toList());
// how to set price field from value of the key
}
}
class Response{}{
String name;
Long code;
String city;
Long price;
public static Response fromString(String key, Long value){
Response res = new Response();
String[] keys = key.split("//-");
// some logic to set name and city
res.name = keys[0];
if(keys.length == 2) {
if(keys[1].matches("-?\\d+(\\.\\d+)?") // check if string is numeric
{
res.code = keys[1]
}
else{
res.city = keys[1]
}
}
res.price = value;
return res;
}
}
最佳答案
在Response
类中创建一个构造函数,接受两个参数并初始化相应的属性
class Response {
String name;
String city;
Long price;
public Response(String key, Long price) {
this.price=price;
String[] keys = key.split("-");
//check conditions and set values to properties
this.name = keys[0];
this.city = keys[1];
}
}
现在使用stream
和map
转换成Response
对象
List<Response> list = map.entrySet().stream().map(entry -> new Response(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
关于java - 如何使用 java 8 流将 HashMap 的值设置为自定义 java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021628/