Sunday, December 28, 2014

Quick 2-tuples in Java

For cases one does not want or need (because it would never find reuse!) to create wrapper class for pairing two values of any types (a 2-tuple) in Java, Map.Entry public inner interface in java.util.Map container can be acceptable alternative. Code relying on java.util.Collections.singletonMap (constant additional space use!) to return a pair from Java method can be written as such:

// returns pair (2-tuple)
private Map.Entry<Integer, Record> bar() {
  // ... recordCount and record created
  return Collections.singletonMap(recordCount, record).entrySet().iterator().next();
}

// 2-tuple extraction with getKey()/getValue()
public void foo() {
  Map.Entry<Integer, Record> pair = bar();
  Integer recordCount = pair.getKey();
  Record record = pair.getValue();
  // use paired values ...
}

No comments:

Post a Comment