0

I'm trying to format the data inside my HashMap according to their key.

I have a loop which prints data in the following format

icon: "rain"
windBearing: 239
ozone: 339.89
precipType: "rain"
humidity: 0.82
moonPhase: 0.98
windSpeed: 7.37
summary: "Light rain starting in the evening."
visibility: 16.09
cloudCover: 0.62
pressure: 1011.49
dewPoint: 1.26
time: 08-03-2016 00:00:00
temperatureMax: 8.09

All of this data is stored in a HashMap with key (for example) icon and value "rain".

How can I format all of this data according to their keys? I tried something like this

private Map formatter(Map data) {
    String tmp;
    for(int i = 0; i < data.size(); i++) {
        if(data.containsKey("temperatureMax")) {
            tmp = String.format("%s c TEST", data.get("temperatureMax"));
            data.put("temperatureMax", tmp);
        }
    }
    return data;
}

I thought something like this would format 8.09 to simply 8, but it didn't do anything. (I attempted to do what the answer here How to update a value, given a key in a java hashmap? states)

This is where I acquire the data.

public Map dailyReport() {
    FIODaily daily = new FIODaily(fio);
    //In case there is no daily data available
    if (daily.days() < 0) {
        System.out.println("No daily data.");
    } else {
        System.out.println("\nDaily:\n");
    }
    //Print daily data
    for (int i = 0; i < daily.days(); i++) {
        String[] value = daily.getDay(i).getFieldsArray();
        System.out.println("Day #" + (i + 1));
        for (String key : value) {
            System.out.println(key + ": " + daily.getDay(i).getByKey(key));
            dailyData.put(key, daily.getDay(i).getByKey(key));
            formatter(dailyData);
        }
        System.out.println("\n");
    }
    return dailyData;
}
Community
  • 1
  • 1
  • `dailyData` needs to be a map for _just one day_. You need an array of HashMaps, then do `dailyData[i].put(...);` – Klitos Kyriacou Mar 06 '16 at 00:12
  • Also, why are you bothering to put unformatted data into the map and then immediately afterwards update that data? It's more efficient to put the correctly formatted data into the map the first time. Just format the data before you put it into the map. – Klitos Kyriacou Mar 06 '16 at 00:14

1 Answers1

0

You should iterate through your map keys using the keySet() function of Map

for (String name:data.keySet()) {
    if (name.equals("temperatureMax")) {
        //Do your formatting
    }
}
Xiongbing Jin
  • 11,779
  • 3
  • 47
  • 41