Why the method 'replace' does not work properly, using keySet for a Map?

43 Views Asked by At

There is a map (tickets), where the key is the players' tips (as a set) and the value, which is 0 before checking the ticket and should update after checking the tips with the hits. I make an intersection on the tips and the winning numbers for each ticket lines. The new size of the set gives the hit result and should replace in the map. As the result shows below, the key updates well, but the value not. What is the problem?

public void ticketCheck() {
        
    // tickets and winningNumbers will come as parameters, now it is only an example:
    Map<Set<Integer>,Integer> tickets = new HashMap<Set<Integer>,Integer>(){
        {
            put(new HashSet<Integer>(Set.of(5,21,25,32,38,40)) ,0); 
            put(new HashSet<Integer>(Set.of(8,11,17,29,32,45)) ,0); 
        };
    };
        
    Set<Integer> winningNumbers = new HashSet<Integer>(Set.of(11,20,32,33,36,45));
        
    Iterator<Set<Integer>> itr = tickets.keySet().iterator();
    while (itr.hasNext()) {         
            Set<Integer> oneTicket = itr.next();
            oneTicket.retainAll(winningNumbers); // intersection of the tips and winning numbers
            int result = oneTicket.size();  
            tickets.replace(oneTicket,result);
    }
                
    for (Map.Entry<Set<Integer>, Integer> item : tickets.entrySet()) {
        System.out.println(item.getKey() + " hits: "+item.getValue());
    }               
}

The result:

[32] hits: 0
[32, 11, 45] hits: 0

but should be:

[32] hits: 1
[32, 11, 45] hits: 3
0

There are 0 best solutions below