我有一个HashMap
,我想将其转换为自定义对象Response
。我不确定如何将HashMap
中的值(80、190、900、95)设置为自定义对象?如何在Response对象中编写一个单独的函数,该对象设置价格字段或将fromString
函数的两个参数(键和值)设置为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(Response::fromString).collect(Collectors.toList());
// how to set price field from value of the key
}
}
class Response{}{
String name;
String city;
Long price;
public static Response fromString(String key){
Response res = new Response();
String[] keys = key.split("//-");
// some logic to set name and city
res.name = keys[0];
if(keys.length > 1) {
res.city = keys[1];
}
return res;
}
}
您可以尝试这个。
List<Response> list = map.entrySet().stream().map(e ->
{
Response res = new Response();
res.name = e.getKey();
res.price = e.getValue();
return res;
}).collect(Collectors.toList());
}
如果您的班级中有constructor
和getters
,那会更干净。
我只使用方法Map#entrySet()
而不是keySet()
。
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.entrySet().stream().map(Response::fromString).collect(Collectors.toList());
}
}
class Response{}{
String name;
String city;
Long price;
public static Response fromString(Map.Entry<String,Long> entry){
String key=entry.getKey();
Long price=entry.getValue();
Response res = new Response();
String[] keys = key.split("//-");
// some logic to set name and city
res.name = keys[0];
if(keys.length > 1) {
res.city = keys[1];
}
//set price
price=value;
return res;
}
}
在Response
类中创建一个接受两个参数并初始化相应属性的构造函数
class Response {
String name;
String city;
Long price;
public Response(String key, Long value) {
this.value=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());