Skip to content

Instantly share code, notes, and snippets.

@FlorianDe
Created November 6, 2019 09:55
Show Gist options
  • Save FlorianDe/3c07846a61a720c7e02952c991118663 to your computer and use it in GitHub Desktop.
Save FlorianDe/3c07846a61a720c7e02952c991118663 to your computer and use it in GitHub Desktop.
A simple generic tuple (key/value pair) builder with the ability to dynamically filter out null values when trying to add them.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
/**
*
* This class serves as a generic approach to create list containing related key value tuples
* represented within a list while offering the functionality to be able to dynamically filter out (don't add)
* entries where the value would be null as need for some use cases.
*
* The skip mechanism is backed up by the following truth table:
* <p>
* Entry value is null? => V
* Global skip (skipNullValues set to true) => G
* Explicit skip (skipNullValue set to true) => E
* Resulting in an entry addition => A
* <p>
* | V | G | E || A
* -----------------
* | 0 | 0 | 0 || 1
* | 0 | 0 | 1 || 1
* | 0 | 1 | 0 || 1
* | 0 | 1 | 1 || 1
* | 1 | 0 | 0 || 1
* | 1 | 0 | 1 || 0
* | 1 | 1 | 0 || 1
* | 1 | 1 | 1 || 0
* <p>
* => Addition when !(V&&E)
*/
public abstract class TupleListBuilder<K, V extends K> {
private final boolean skipNullValues;
private final List<K> keyValueTupleList = new ArrayList<>();
public TupleListBuilder() {
this(true);
}
public TupleListBuilder(boolean skipNullValues) {
this.skipNullValues = skipNullValues;
}
public TupleListBuilder<K, V> setTag(K key, V value) {
return this.setTag(key, value, this.skipNullValues);
}
public TupleListBuilder<K, V> setTag(K key, V value, boolean skipNullValue) {
if (!(value == null && skipNullValue)) {
synchronized (keyValueTupleList) {
this.keyValueTupleList.add(key);
this.keyValueTupleList.add(value);
}
}
return this;
}
public List<K> build() {
return new ArrayList<>(this.keyValueTupleList);
}
@SuppressWarnings("unchecked")
public K[] buildArray() {
if(this.keyValueTupleList.isEmpty()){
return (K[]) new Object[0];
}
K[] tupleArray = (K[]) Array.newInstance(this.keyValueTupleList.get(0).getClass(), this.keyValueTupleList.size());
for (int i = 0; i < this.keyValueTupleList.size(); i++) {
tupleArray[i] = this.keyValueTupleList.get(i);
}
return tupleArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment