Search code examples
javahashmap

HashMap inside HashMap vs Map.Entry inside HashMap Java


Soo, i need to store a nonce, a user and the user's IP I thought of puting a HashMap inside a HashMap like the following: private Map<BigInteger, HashMap<User, String>> users;

But found that someone instead of doing what I thought of doing, did this:

private Map<BigInteger, Map.Entry<User, String>> users;

(Variable types differ)

But I wanted to know, what would be better and if there's a better way of doing what I'm trying to do. Thanks in advance


Solution

  • Define a class to keep User and IP together.

    @Getter @AllArgsConstructor
    public class SessionInfo {
        private User user;
        private String IP;
    }
    

    and use a map utilizing this class:

    Map<BigInteger, SessionInfo> users;
    

    Note: In the question's example, Map.Entry is used as a class holding two values. A dedicated class is better.

    Note-2: Map in Map is not a good idea for this case. As long as you do not want to have more than one user per nonce, do not use Map in Map.