Hashmap value getting overwritten

时间:2016-10-15 17:12:49

标签: java elasticsearch hashmap

I'm having my Hashmap as such as a global variable within my class:

private Map<String, CodaReportDTO> dateAndDTO = new TreeMap<>(); //hashmap for date and the dto

So the value here is a DTO which has properties which I had to fill in an excel. I'm trying to fill up only one field (which is numOfTxn from the DTO) using the key (the date). So basically i'm trying to print out the values of the DTO per day.

This is my DTO class.

I'm trying to add values here to the hashmap as such for the number of days in a month:

private JSONObject postDataToElasticSearchForSuccessCount(String url, String operatorID) throws IOException, JSONException, ParseException {

    /*JSONObject jsonObject = elasticSearchDataReceiver.getResults(url);

    //getting the number of hits
    JSONObject totalHits = jsonObject.getJSONObject("hits");
    Object hitsCountForSuccessCount = totalHits.get("total");
    String hitCountForSuccessCount = hitsCountForSuccessCount.toString();

    if (Integer.parseInt(hitCountForSuccessCount) > 0) {
        codaReportDTO.setNumOfTxn(Integer.parseInt(hitCountForSuccessCount));
    }
    return new JSONObject(jsonObject.toString());*/

    JSONObject updatedJsonObject = null;
    String jsonBody;
    String monthName = Month.of(Integer.parseInt(excelMonth)).name();
    int numberOfDaysInAMonth = Utilities.getNumberOfDaysForMonth(Integer.parseInt(excelYear), monthName);

    //iterate over the month
    for (int i = 1; i < numberOfDaysInAMonth; i++) {


        String day = appendZeroToDay(i);
        excelDateMonth = day + "-" + excelMonth;
        Date excelMonthOriginal = new SimpleDateFormat("dd-MM").parse(excelDateMonth);
        String formattedDate = String.valueOf(excelMonthOriginal);
        String MonthOnly = formattedDate.substring(4, 7);
        String DateOnly = formattedDate.substring(8, 10);
        String dateAndMonthFinal = DateOnly + "-" + MonthOnly;
        excelDateMonth = dateAndMonthFinal;

        String input = "{  \n" +
                "   \"query\":{  \n" +
                "      \"query_string\":{  \n" +
                "         \"query\":\"api:\\\"smsmessaging\\\" AND operatorid:" + operatorID + " AND transactionOperationStatus:\\\"\\\" AND responsecode:(200 201) AND year:" + excelYear + " AND month:" + excelMonth + " AND day:" + day + "\"\n" +
                "      }\n" +
                "   },\n" +
                "   \"aggs\":{  \n" +
                "      \"total\":{  \n" +
                "         \"terms\":{  \n" +
                "            \"field\":\"userid\"\n" +
                "         },\n" +
                "         \"aggs\":{  \n" +
                "            \"grades_count\":{  \n" +
                "               \"value_count\":{  \n" +
                "                  \"script\":\"doc['userid'].value\"\n" +
                "               }\n" +
                "            }\n" +
                "         }\n" +
                "      }\n" +
                "   }\n" +
                "}\n";

        jsonBody = input;
        JSONObject jsonObject = elasticSearchDataReceiver.getResult(url, jsonBody);

        JSONObject totalHits = jsonObject.getJSONObject("hits");
        Object hitsCountForSuccessCount = totalHits.get("total");
        String hitCountForSuccessCount = hitsCountForSuccessCount.toString();
        int hitCount = Integer.parseInt(hitCountForSuccessCount);

        if (hitCount > 0) {
            updatedJsonObject = jsonObject;
            codaReportDTO.setNumOfTxn(hitCount);
            dateAndDTO.put(dateAndMonthFinal, codaReportDTO);
        }
    }
    return updatedJsonObject;
}

The hashmap adding part is at the bottom of the above snippet:

dateAndDTO.put(dateAndMonthFinal, codaReportDTO);

The key and the value is coming correctly in the above line. But when it tries to update the value for the new key, it replaces the other values of keys which have values with the new value. Where am I going wrong?

I've been trying this for the whole day after looking into other question here in the SO, but still couldn't get through. Any help could be appreciated.

2 个答案:

答案 0 :(得分:2)

You are using the same instance of your DTO for all the map's entries. This is why, each change is reflected on all values. If you dont want changes to be overriden, you need to create a new instance for each of the map's keys.

答案 1 :(得分:1)

地图的使用方式存在问题。如果要对同一个密钥使用多个值,则应使用List&lt;&gt;作为Map<String, List<CodaReportDTO>>

的第二个参数