Java Equivalent of PHP's implode with Filtering
In PHP, chaining functions like array_filter, array_values, and implode is a common idiom for cleaning up loose data structures before serialization. The specific pattern you are looking at filters out empty strings from an array of address components (postal code, city, province) and joins the remaining items with a comma and space. It handles edge cases gracefully: if no data remains, it returns an empty string; if only one item exists, it avoids trailing delimiters.
Translating this directly to Java without external libraries requires shifting from procedural array manipulation to functional streams or careful list management. Since you are designing for Android, we must prioritize standard library solutions that work on the JVM and do not rely on heavy dependencies like Guava or StreamEx, which add bloat to APK sizes.
The Functional Approach with Streams
The most idiomatic Java 8+ equivalent uses Stream APIs. This approach mimics the PHP logic closely: filter out empty strings, convert the resulting stream into a list (or collect directly), and then join them.
Here is how you can implement the logic using Collectors.joining:
import java.util.*;
import java.util.stream.*;
public class AddressFormatter {
public static String formatAddress(String cap, String citta, String provincia) {
List<String> parts = Arrays.asList(cap, citta, provincia);
return parts.stream()
.filter(part -> part != null && !part.trim().isEmpty())
.map(String::trim) // Optional: removes leading/trailing whitespace if input is dirty
.collect(Collectors.joining(", ", "", ""));
}
}
The Collectors.joining(CharSequence delimiter, String prefix, String suffix) collector is key here. By passing an empty string for both the prefix and suffix, we ensure that no commas are added at the start or end of the result. The stream automatically handles the case where no elements pass the filter; the resulting string will simply be empty, matching your PHP requirement.
The Iterative Approach for Performance
While Streams are concise, they create intermediate objects and iterate twice (once to filter, once to collect). If performance is critical on low-end Android devices or within tight loops, a traditional StringBuilder approach might be more efficient. This method avoids the overhead of stream allocation and provides finer control over the logic.
public static String formatAddressIterative(String cap, String citta, String provincia) {
List<String> parts = Arrays.asList(cap, citta, provincia);
StringBuilder sb = new StringBuilder();
boolean hasContent = false;
for (String part : parts) {
if (part != null && !part.trim().isEmpty()) {
if (hasContent) {
sb.append(", ");
}
sb.append(part);
hasContent = true;
}
}
return sb.toString();
}
This implementation explicitly manages the delimiter insertion. The hasContent flag ensures that a comma-space is only appended if a previous valid element was found, preventing the "extra comma" issue seen in naive implementations. It also avoids creating a new List or Stream collector instance for every call, which reduces garbage collection pressure.
Handling Nulls and Whitespace
A crucial detail often overlooked when porting from PHP to Java is the strictness of null handling. In PHP, array_filter with the default callback removes both empty strings and null values. If you translate this naively in Java using .filter(Objects::nonNull), you might miss empty strings ("").
The filter condition part != null && !part.trim().isEmpty() covers both scenarios. Note that calling .trim() on an empty string returns the same empty string, so checking for emptiness after trimming is a robust way to handle inputs like " " or "\n". This ensures your address string remains clean regardless of how the frontend populated the fields.
Why Not Use a Library?
You might wonder if there is a utility class that does this automatically. While libraries like Apache Commons Lang offer join methods, they often require importing extra dependencies. In the Android ecosystem, keeping the dependency graph minimal is a standard practice to reduce APK size and startup latency. The standard library's Stream API or a simple StringBuilder loop provides 99% of the functionality needed for address formatting without any external overhead.
If you find yourself doing this logic repeatedly across multiple projects, consider extracting it into a utility class within your own codebase. This keeps the main business logic clean while adhering to the "no external libraries" constraint.