Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value of HashMap into a custom java object using java 8 stream?

I have a HashMap which I want to convert to custom object Response. I am not sure how to set the values (80, 190, 900, 95) from HashMap to the custom object? How to write a separate function in Response object which sets price fields or set two parameters (key and value) to fromString function.

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;
  }
}
like image 657
Nishant Avatar asked Jan 20 '26 03:01

Nishant


1 Answers

Create a constructor in Response class that accepts two parameters and initialize the corresponding properties

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

Now use stream and map to convert into Response object

List<Response> list = map.entrySet().stream().map(entry -> new Response(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());
like image 195
Deadpool Avatar answered Jan 22 '26 17:01

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!