Skip to content

Commit 12a2ff4

Browse files
committed
Document that the list of header names will not contain null names.
Added a test to demonstrate missing null headers from the list.
1 parent bd17fc3 commit 12a2ff4

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

src/main/java/org/apache/commons/csv/CSVParser.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,11 @@ public String getFirstEndOfLine() {
555555
* <p>
556556
* The map keys are column names. The map values are 0-based indices.
557557
* </p>
558+
* <p>
559+
* Note: The map can only provide a one-to-one mapping when the format did not
560+
* contain null or duplicate column names.
561+
* </p>
562+
*
558563
* @return a copy of the header map.
559564
*/
560565
public Map<String, Integer> getHeaderMap() {
@@ -577,8 +582,14 @@ Map<String, Integer> getHeaderMapRaw() {
577582

578583
/**
579584
* Returns a read-only list of header names that iterates in column order.
585+
* <p>
586+
* Note: The list provides strings that can be used as keys in the header map.
587+
* The list will not contain null column names if they were present in the input
588+
* format.
589+
* </p>
580590
*
581591
* @return read-only list of header names that iterates in column order.
592+
* @see #getHeaderMap()
582593
* @since 1.7
583594
*/
584595
public List<String> getHeaderNames() {

src/test/java/org/apache/commons/csv/CSVParserTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,20 @@ public void testHeadersMissingOneColumnException() throws Exception {
724724
assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withHeader().parse(in).iterator());
725725
}
726726

727+
@Test
728+
public void testHeadersWithNullColumnName() throws IOException {
729+
final Reader in = new StringReader("header1,null,header3\n1,2,3\n4,5,6");
730+
final Iterator<CSVRecord> records = CSVFormat.DEFAULT
731+
.withHeader()
732+
.withNullString("null")
733+
.withAllowMissingColumnNames()
734+
.parse(in).iterator();
735+
final CSVRecord record = records.next();
736+
// Expect the null header to be missing
737+
assertEquals(Arrays.asList("header1", "header3"), record.getParser().getHeaderNames());
738+
assertEquals(2, record.getParser().getHeaderMap().size());
739+
}
740+
727741
@Test
728742
public void testIgnoreCaseHeaderMapping() throws Exception {
729743
final Reader reader = new StringReader("1,2,3");

0 commit comments

Comments
 (0)