Search code examples
javahashmapcomparison

Hashmap same values different key comparison


My HashMap of type contains

    String storeId = "3501";
    HashMap<String,String> hMap =  new HashMap<>();
    hMap.put("01",105);
    hMap.put("02",3501);
    hMap.put("07",3501);

    for (int mainLoop=0; mainLoop < 3 ;mainLoop++){
    for (Map.Entry<String, String> map : hMap.entrySet()) {
                    if (storeId.equalsIgnoreCase(map.getValue())) {
                        fulFillmentType = map.getKey();
                    }
                }
    }

Each time mainLopp is executed. When it hits "3501" first time only "02" should be return and hitting "3501" on third loop should return "07". Currently output is only "07"


Solution

  • I suggest that the issue is that you are not keeping track of state for all matching keys. If you want to keep track of all matching keys, then consider using a collection of strings:

    String storeId = "3501";
    HashMap<String,String> hMap =  new HashMap<>();
    hMap.put("01", "105");
    hMap.put("02", "3501");
    hMap.put("07", "3501");
    
    List<String> matches = new ArrayList<>();
    
    for (int mainLoop=0; mainLoop < 3 ;mainLoop++) {
        for (Map.Entry<String, String> map : hMap.entrySet()) {
            if (storeId.equalsIgnoreCase(map.getValue())) {
                matches.add(map.getKey());
            }
        }
    }
    
    matches.forEach(System.out::println);
    

    Note that in your original question, the values of the hMap were integer literals, not strings. They would need to be strings enclosed in double quotes in order for your code to even compile.