Preserve empty fields in an order record in Java
A negative split limit retains a trailing empty field. This matters when an optional field has a defined position, even when the sender leaves it blank.
A simple example
Split with trailing fields retained
- Start with A comma after A
- Do this Split with trailing fields retained
- Result A and an empty field
Apply it to a real problem
- Start with Order A42 with quantity 2 and a blank final field
- Do this Split at each vertical bar
- Result Three columns
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
String line = "A42|2|";
System.out.println(Arrays.toString(line.split("\\|", -1)));
System.out.println(line.split("\\|", -1).length + " columns");
}
}
[A42, 2, ] 3 columns