java - 如何使用 java 8 流将 HashMap 的值设置为自定义 java 对象?

标签 java java-8 java-stream

我有一个 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];
  }
}

现在使用streammap转换成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/

相关文章:

java - 在simpleCaptcha中更改图像样式

lambda - Java 8 - 如何使用流收集器对 map 列表进行分组和求和

java - 使用 Java 8 Stream API 进行计数和排序

Java 8流 "Cannot use this in a static context"

java - 如何将音频文件.wav或语音识别转换为文本,Android Studio

java - struts中的request.getParameterValues

java - 仅过滤掉列表中与某些元素匹配的第一个元素的替代方法

java - 从重复逻辑基于自定义字段的列表中删除重复项

java - Java 中的 ImageIcon 更新(来自互联网)?

java - 仅在 apache-tomcat-9 和 Java 8 中启用 TLS 1.2