Home > Enterprise >  How to access a previously mapped value in Java stream API
How to access a previously mapped value in Java stream API

Time:05-08

I'm parsing a JSON as a DTO (CryptoCoinResponse) as follow:

{
   "data":[
      {
         "quote":{
            "USD":{
               "price":35957.144434663925,
               "volume_24h":22208499250,
               "market_cap":684385813954
            }
         },
         "id":"bitcoin"
      }
   ]
}

and trying to convert every object inside "data" to a Entity using stream API. I tried to do as follow:

  public static List<CryptoCurrency> parseDtoToEntity(CryptoCoinResponse crypto){
        return crypto.getData().stream()
                .map(CryptoCoinResponse.Data::getQuote)
                .map(CryptoCoinResponse.Quote::getUsd)
                .map(usd ->
                        new CryptoCurrency(
                                data.getId(),
                                usd.getPrice(),
                                usd.getMarket_cap(),
                                usd.getPrice(),
                                LocalDateTime.now()))
                .collect(Collectors.toList());
    }

but I cannot access id property (data.getId()) from previouysly map. My solution was to do as follow:

    public static List<CryptoCurrency> parseDtoToEntity(CryptoCoinResponse crypto){
        return crypto.getData().stream()
                .map(data ->
                        new CryptoCurrency(
                                data.getId(),
                                data.getQuote().getUsd().getPrice(),
                                data.getQuote().getUsd().getMarket_cap(),
                                data.getQuote().getUsd().getPrice(),
                                LocalDateTime.now()))
                .collect(Collectors.toList());

and I was wondering, is this a better way to do it?

Thanks in advance

CodePudding user response:

The best way is to use Jackson https://mkyong.com/java/jackson-how-to-parse-json/

CodePudding user response:

To avoid duplicating the getQuote().getUSD(), why don't we expand the single-line lambda function and declare a variable inside it called usd:

crypto.getData().stream()
    .map(data -> {
        // Unpack USD here so that we can avoid repeating "getQuote().getUSD()" later
        var usd = data.getQuote().getUsd();
        return new CryptoCurrency(
            data.getId(),
            usd.getPrice(),
            usd.getMarket_cap(),
            usd.getPrice(),
            LocalDateTime.now());
    }).collect(Collectors.toList());

If we wanted to use other parts of the data repeatedly, such as data.getQuote(), then we could declare other variables.

  • Related