Skip to content

Commit 6f170af

Browse files
authored
remove null assignments and check that the map is not empty check (#479)
* remove null assignments and check that the map is not empty check * return an empty string if mode receives an empty map, add test for empty dataset * run spotless fix typo
1 parent e16cb21 commit 6f170af

2 files changed

Lines changed: 31 additions & 12 deletions

File tree

src/main/java/com/teragrep/pth10/ast/commands/aggregate/UDAFs/BufferClasses/ModeBuffer.java

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@
4545
*/
4646
package com.teragrep.pth10.ast.commands.aggregate.UDAFs.BufferClasses;
4747

48+
import com.teragrep.pth10.ast.NullValue;
49+
4850
import java.io.Serializable;
4951
import java.util.Map;
5052

@@ -93,18 +95,12 @@ public void mergeMap(Map<String, Long> another) {
9395
* @return most frequent entry as a string
9496
*/
9597
public String mode() {
96-
Map.Entry<String, Long> mostFrequentEntry = null;
97-
98-
for (Map.Entry<String, Long> entry : this.map.entrySet()) {
99-
if (mostFrequentEntry == null) {
100-
mostFrequentEntry = entry;
101-
}
102-
else if (mostFrequentEntry != null && entry.getValue() > mostFrequentEntry.getValue()) {
103-
mostFrequentEntry = entry;
104-
}
105-
}
106-
107-
return mostFrequentEntry.getKey();
98+
return map
99+
.entrySet()
100+
.stream()
101+
.max(Map.Entry.comparingByValue()) // find max value
102+
.map(Map.Entry::getKey) // select key
103+
.orElse(new NullValue(NullValue.Type.EMPTY_STRING).value()); // if an empty map returns an empty string
108104
}
109105

110106
}

src/test/java/com/teragrep/pth10/statsTransformationTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,29 @@ void statsTransform_AggMode_Test() {
358358
});
359359
}
360360

361+
@Test
362+
@DisabledIfSystemProperty(
363+
named = "skipSparkTest",
364+
matches = "true"
365+
)
366+
void statsTransformAggModeTestEmptyDataset() {
367+
streamingTestUtil
368+
.performDPLTest(
369+
"index=index_A earliest=2020-10-10T11:20:10.100+03:00 | stats mode(offset)", testFile, ds -> {
370+
Assertions.assertEquals("[mode(offset)]", Arrays.toString(ds.columns()));
371+
372+
List<Object> destAsList = ds
373+
.select("mode(offset)")
374+
.collectAsList()
375+
.stream()
376+
.map(r -> r.getAs(0).toString())
377+
.collect(Collectors.toList());
378+
379+
Assertions.assertEquals(Collections.singletonList(""), destAsList);
380+
}
381+
);
382+
}
383+
361384
// Test min()
362385
@Test
363386
@DisabledIfSystemProperty(

0 commit comments

Comments
 (0)