How to prevent Hashmap from overriding the same key with different values

hashmap with multiple values under the same key in java
single key multiple values java hashmap
multiple key-value pair in java
which collection allows duplicate keys in java
put multiple values in hashmap java
how to find duplicate keys in hashmap
java map with duplicate keys
linkedhashmap duplicate keys

i have a code like follows where i am using a hashmap to store the details of segments created but the Hashmap is overriding the last value for all the keys.

but the response i am getting is like follows

0->47 {id=48 name= At_48,code=14512455......}
1->48 {id=48 name= At_48,code=14512455......}

i am getting all the responses overridden by last result ,how to solve this problem

You're using in every iteration the same segmentInformation. Thus it is the only value in returnMap, put for every key.

You need to create a new SegmentInformation in every iteration step and put this one in the map. The problem you stated in your comment is that you are using the segmentInformation already before the for-loop. This is only the case if audienceDataMap.isEmpty(). I suggest you to separate this code from code of the loop.

  private Single<Map<String, CreationResponse>> createSegment(List<Integer> audienceIds) {
    try {
      createToken();
    }
    catch (ValidationServiceException e) {
      SegmentInformation segmentInformation = new SegmentInformation();
      segmentInformation.setError(SEGMENT_CREATION_EXCEPTION.getMessage());
      Map<String, CreationResponse> returnMap = new HashMap<>();
      returnMap.put(segmentInformation.getAudienceId().toString(), segmentInformation);
      logger.error(TOKEN_CREATION_EXCEPTION.getMessage());
    }
    catch (IOException e) {
      SegmentInformation segmentInformation = new SegmentInformation();
      segmentInformation.setError(SEGMENT_CREATION_EXCEPTION.getMessage() + SEGMENT_CODE_EXIST.getMessage());
      Map<String, CreationResponse> returnMap = new HashMap<>();
      returnMap.put(segmentInformation.getAudienceId().toString(), segmentInformation);
      logger.error(SEGMENT_CREATION_EXCEPTION.getMessage());
    }

    List<ListBasedAudienceFetcher.AcAudience> audienceDataMap = audienceIds != null ?
      impl.processAudienceByIds(audienceIds) :
      impl.processAudience();

    if (audienceDataMap.isEmpty()) {
      SegmentInformation segmentInformation = new SegmentInformation();
      segmentInformation.setError(PROGRAMS_NOT_CREATED.getMessage());
      Map<String, CreationResponse> returnMap = new HashMap<>();
      returnMap.put(CREATE_PROGRAM.getMessage(), segmentInformation);
      return Single.just(returnMap);
    }

    Map<String, CreationResponse> returnMap = new HashMap<>();
    for (ListBasedAudienceFetcher.AcAudience audienceData : audienceDataMap) {
      SegmentInformation segmentInformation = new SegmentInformation();
      segmentInformation.setMemberId(memberId);
      segmentInformation.setAudienceId(audienceData.getId());
      String audienceName = getSegmentName(audienceData);
      segmentInformation.setAudienceName(audienceName);
      try {
        String createSegmentResponse = Util.post(new PayLoad()
          .setUrl(AppNexusConstants.APPNEXUS_SEGMENT_URL + "/" + memberId)
          .setRequestType(Request.POST)
          .setHeader(getAppnexusAuthHeader())
          .setPayload(createSegmentPayload(audienceData, memberId)));
        SegmentResponse segmentResponse = Util.mapper.readValue(createSegmentResponse, SegmentResponse.class);
        if (segmentResponse != null
          && segmentResponse.getResponse().getStatus() != null
          && segmentResponse.getResponse().getStatus().equals("OK")) {
          BillingData billingData = billingSegment(audienceData, segmentResponse.getResponse().getSegmentData());
          segmentResponse.getResponse().getSegmentData().setBillingData(billingData);
        } else {
          segmentInformation.setError(SEGMENT_CREATION_EXCEPTION.getMessage() + audienceData.getId());
        }
        segmentInformation.setSegmentCreationResponses(segmentResponse);
        returnMap.put(audienceData.getId().toString(), segmentInformation);
      }
      catch (IOException e) {
        segmentInformation.setError(SEGMENT_CREATION_EXCEPTION.getMessage() + SEGMENT_CODE_EXIST.getMessage());
        returnMap.put(segmentInformation.getAudienceId().toString(), segmentInformation);
        logger.error(SEGMENT_CREATION_EXCEPTION.getMessage());
      }
    }

    return Single.just(returnMap);
  }

Please note that I also moved the declaration of billingData in the if-block where it is initialized.

How to Store Duplicate Keys in a Map in Java?, Java has several implementations of the interface Map, each one with its own particularities. As we can see, if we try to insert two values for the same key, the second Map<String, List<String>> map = new HashMap<>(); like restrictive company policies preventing us from using third-party libraries. HashMap – Single Key and Multiple Values Example Sometimes you want to store multiple values for the same hash key. The following code examples show you three different ways to do this.

Creating HashMap by associating multiple values with same Key, Java : Creating HashMap by associating multiple values with same Key Suppose we want to create a HashMap to keep the track of strings and their Let's Create a HashMap of String as Key and List<Integer> as value i.e. System Programming (8) List (29) Method Overriding (5) Multithreading (12)  To store this data in a lookup table / map , we need to create a HashMap with key as string and then associate multiple values with same key. We can do this by storing a List of Integers i.e. List<Integer> objects as values in HashMap. HashMap with List<T> Object as Value. Let’s Create a HashMap of String as Key and List<Integer> as value i.e.

Sorry men I can't still post just comments, the problem you have is that the hashmethod you are using to generate you key shouldn't be returning the same hashcode, the whole idea behind hashing lost the sense if two values share the same key. change the key generator method.

regards!

Java Map, The HashMap implementation is typically the fastest of the two Map The generic type helps you avoid inserting the wrong objects, and makes it easier Of course you can store values for the same key in different Map instances. same key, the latest value passed to put() for that key will overwrite what is  1. The problem with a map is that you can assign only one value per key 2. To assign several values per key, we suggested you to use a Map<String, List><String>>. The values are stored in a List, and the List is assigned to the key of the map Try to find out how : 1. To iterate through the Map. What is the type of each value ?

Difference between HashSet and HashMap, HashMap does not allow duplicate keys however it allows to have duplicate values. HashSet permits to have a single null value. HashMap permits single null key  Let’s note down the internal working of put method in hashmap. First of all, the key object is checked for null. If the key is null, the value is stored in table[0] position. Because hashcode for null is always 0. Then on next step, a hash value is calculated using the key’s hash code by calling its hashCode() method.

How to join or merge two hashmaps in Java, cases - ignore duplicate keys (overwrite values) or handle duplicate keys using Java 8. As we know hashmap does not allow duplicate keys. So when we merge the maps in this way, for duplicate keys in map1 the value is is found ONLY WHEN the value is different from previous values associated with key in map1 . 1. Compare hashmap for same key-values – HashMap.equals() By default, HashMap.equals() method compares two hashmaps by key-value pairs. It means both hashmap instances must have exactly same key-value pairs and both must be of same size. The order of key-value pairs can be different and does not play in role in comparison.

Why HashMap not allowing duplicate keys? How it is stored?, A hashmap is a data structure that stores 4 elements key, value, hashValue and a I'll simply override the value since hashmap is key based and no 2 key can be same. linear probing, quadratic probing and double hashing to avoid those . While other implementations of Map might allow for duplicate keys, HashMap  In Hash map equals method works on keys. Generally Hash code is may same or may not same for two different keys. if hash code is same and and the index is same but keys are different In this case hash map create a linked list and stores the values at the next node of present key value pair

Comments
  • You're using in every iteration the same segmentInformation. Thus it is the only value in your map, put for every key.
  • correct me if i am wrong, that means i should place the SegmentInformation declaration inside the for loop
  • Yes ... create a new SegmentInformation segmentinformation in every iteration step.
  • but there is a problem that SegmentInformation segmentinformation is also used outside the forloop so if i define it inside the forloop only how can it can be accessed outside the loop.
  • Why do you need it outside the loop?
  • hi lucio i am sorry i said wrongly that exception is thrown only by createToken actually the code inside the for loop is also throwing IO exception so that should also be handled
  • Which method throws it?
  • Util class has methods that is throwing IO exception
  • but audienceDataMap is not accesible here now for (ListBasedAudienceFetcher.AcAudience audienceData : audienceDataMap) {
  • @Ikshwak I moved audienceDataMapout of the try-catch-block. Now it is visible for the for-loop.