Search code examples
javahashmap

Reteun obj in hashmap in Java


I have a model which is named PeerModel is written with JSON. In another class, I set this model as a key of a HashMap.

Map<PeerModel,Boolean> peers = new HashMap<>(); 

now I have a method and I need to check if the value is false, return the model(which is key of the HashMap). This is the code but it returns null.

public PeerModel getUnusedPeer() {
    for (int i = 0; i < peers.size(); i++)
        if (peers.containsValue(i) == false)

            return new PeerModel();
}

Solution

  • If you are sure that there is only one false value in the map (Since your method return only one PeerModel object), you can use something like :

    Optional<PeerModel> optional = peers.entrySet().stream()
      .filter(e -> !e.getValue())
      .map(Map.Entry::getKey)
      .findFirst();