我有一个HashMap
要转换为自定义对象的对象Response
。我不确定如何将值(80、190、900、95)HashMap
设置为自定义对象?如何在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;
}
}
我必须修复您的代码中在语法上不正确的一些问题。
L
我加了
toString
让您看到Response类内容的方法。
public class Converter {
public static void main(String[] args) {
Map<String, Long> map = new HashMap<>();
map.put("111", 80L); // first
map.put("1A9-ppp", 190L); // second
map.put("98U-6765", 900L); // third
map.put("999-aa", 95L); // fourth
List<Response> list = map.entrySet().stream().map(
ent -> Response.instanceOf(ent.getKey(), ent.getValue())).collect(
Collectors.toList());
System.out.println(list);
}
}
class Response {
String name;
String city;
long price;
public Response(String name, String city, long price) {
this.name = name;
this.city = city;
this.price = price;
}
public static Response instanceOf(String str, long price) {
if (str.indexOf("-") == -1) {
str += "-NoName";
}
String[] items = str.split("-");
return new Response(items[0], items[1], price);
}
public String toString() {
return "name = " + name + ", city = " + city + ", " + "price = " + price;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句