Xenon
Xenon

Reputation: 311

How can I iterate through an array list of pairs to retrieve the value of a specified key?

I have been trying to write a function Retrieve in Java that accepts a key and returns a value from an array list of Pairs. Any suggestions?

  ArrayList<Pair<K,V>> set_of_pairs = new ArrayList<Pair<K,V>>();
  public void insert(K key, V value) {
    Pair<K,V> pair = new Pair<K,V>(key,value);
    set_of_pairs.add(pair); 
  }

  public void traverse(Visitor<K,V> visitor) {       
  }

  public V retrieve(K key) {
   int i = 0;
   if (set_of_pairs.containsKeys(key) == false) {
      return null;
   }
   else {
      for(Pair<K,V> set_of_pairs: pair) {
         if (pair.getKey() == key) {
            return pair.getValue();
         }
      }      
    }
  }

Upvotes: 3

Views: 6771

Answers (1)

Naman
Naman

Reputation: 31928

You can correct your logic of retrieve method as:

public V retrieve(K key) {
    // iterating on each element of the list would suffice to check if a key exists in the list 
    for (Pair<K, V> pair : set_of_pairs) { // iterating on list of 'Pair's
        if (pair.getKey().equals(key)) {  // 'equals' instead of ==
            return pair.getValue();
        }
    }
    return null;
}

Further, this can be simplified to a logic using the and adapted as pointed by shmosel

public V retrieveUsingStreams(K key) {
    return set_of_pairs.stream()
            .filter(pair -> pair.getKey().equals(key)) // the 'if' check
            .findFirst() // the 'return' in your iterations
            .map(Pair::getValue) // value based on the return type
            .orElse(null); // else returns null
}

Upvotes: 1

Related Questions