dimanche 31 mars 2019

HashMap put method doesn't add data

I'm trying to compare two HashMaps while retrieving the data from a database with sql query(JUnit Test). I get the data perfectly from the database but for some reason one of the HashMap stay empty.

I have checked that the query is working and indeed getting the data I need and tried to use ArrayList and a simple array to store the data, which both of them works.

@Autowired
EntityManager em;

@Test
public void totalScore() {

    //First query
    String qs = "select driver.id, n_safety_events from driver join "
            + "trips_matches on driver.id=trips_matches.driver_id join "
            + "trips on trips.id=trips_matches.trip_id ";

    //Second query
    String qs2 = "SELECT daily_driver_scores.driver_id, daily_driver_scores.n_events FROM daily_driver_scores";


    //Get the data from the database to List
    Query getExpectedResultQuery = em.createNativeQuery(qs);
    Query getActualResultQuery = em.createNativeQuery(qs2);

    List<Object[]> expectedResultList = getExpectedResultQuery.getResultList();

    List<Object[]> actualResultList = getActualResultQuery.getResultList();

    HashMap<Integer, Integer> expectedResult = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> actualResult = new HashMap<Integer, Integer>();

    //Work properly 
    for (Object[] item : expectedResultList) {
        try {
            int driverId = Integer.parseInt(item[0].toString());
            int numberOfSafetyEvents = Integer.parseInt(item[1].toString());

            //If the key is already exits add to his value, else just put the value
            expectedResult.put(driverId,
                    expectedResult.containsKey(driverId) ? expectedResult.get(driverId) + numberOfSafetyEvents
                            : numberOfSafetyEvents);

        } catch (Exception e) {
            // log.error(e.getMessage(), e);
        }
    }

    //Exactly same as the expected but dosen't work
    for (Object[] item : actualResultList) {
        try {

            int driverId = Integer.parseInt(item[0].toString());
            int numberOfSafetyEvents = Integer.parseInt(item[1].toString());

            actualResult.put(driverId,
                    actualResult.containsKey(driverId) ? actualResult.get(driverId) + numberOfSafetyEvents
                            : numberOfSafetyEvents);

        } catch (Exception e) {
            // log.error(e.getMessage(), e);
        }
    }

    assertEquals(actualResult, expectedResult);
}

So in the second for (the actual result) I get the data (driverId and numberOfSafetyEvents isn't 0 or null) but when I use the put nothing happend. I have used debugger mode to see if some value are overwritten in the hashmap but for the whole time the actualResult HashMap staying the same.

Am I doing something wrong? because to me the first for and the second for is the same.

Aucun commentaire:

Enregistrer un commentaire