Skip to content
Permalink
Browse files

add Record.get default value (#489)

  • Loading branch information
MykolaGolubyev committed Jan 9, 2020
1 parent 626cf11 commit e55877782298e93f892fd360b2a084a87caaba55
@@ -58,12 +58,27 @@ public CompositeKey getKey() {
return (E) values.get(header.columnIdxByName(name));
}

@SuppressWarnings("unchecked")
public <E> E get(String name, E defaultValue) {
int idx = header.findColumnIdxByName(name);
return idx ==-1 ? defaultValue : (E) values.get(idx);
}

@SuppressWarnings("unchecked")
public <E> E get(int idx) {
header.validateIdx(idx);
return (E) values.get(idx);
}

@SuppressWarnings("unchecked")
public <E> E get(int idx, E defaultValue) {
if (idx < 0 || idx >= values.size()) {
return defaultValue;
}

return (E) values.get(idx);
}

public Stream<Object> valuesStream() {
return values.stream();
}
@@ -111,6 +111,16 @@ public String toString() {
return namesByIndex.toString();
}

/**
* column index by column name
* @param columnName column name to get index for
* @return column index or -1 if not found
*/
public int findColumnIdxByName(String columnName) {
Integer idx = indexByName.get(columnName);
return idx == null ? -1: idx;
}

/**
* column index by column name
* @param columnName column name to get index for
@@ -39,4 +39,26 @@ class RecordTest {
def record = new Record(new Header(["c1", "c2", "c3"].stream()), ["v1", "v2", "v3"].stream())
assert record.key == null
}

@Test
void "should return defaultValue if a columnName is not present"() {
def record = new Record(new Header(["c1", "c2", "c3"].stream()), ["v1", "v2", "v3"].stream())
def valueC1 = record.get("c1", 42)
def valueColNotFound = record.get("notPresentColumn", 42)

assert valueC1 == "v1"
assert valueColNotFound == 42
}

@Test
void "should return defaultValue if an idx is not present"() {
def record = new Record(new Header(["c1", "c2", "c3"].stream()), ["v1", "v2", "v3"].stream())
def valueC2 = record.get(1, 42)
def valueColNotFound = record.get(3, 42)
def valueColInvalidIdx = record.get(-1, 42)

assert valueC2 == "v2"
assert valueColNotFound == 42
assert valueColInvalidIdx == 42
}
}

0 comments on commit e558777

Please sign in to comment.
You can’t perform that action at this time.