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

问题描述 投票:0回答:3

我有一个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;
  }
}
java java-8 stream
3个回答
0
投票

您可以尝试这个。

      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());
   }

如果您的班级中有constructorgetters,那会更干净。


0
投票

我只使用方法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;
    }
}

0
投票

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];
  }
}

现在使用streammap转换为Response对象

List<Response> list = map.entrySet()
                         .stream().map(entry->new Response(entry.getKey(),
                                                         entry.getValue()))
                          .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.