I'm creating a human-readable list from the keys of a map
object. I want it to be comma-separated, but include the word "and" at the end before the last element, supplying a given locale for the word "and".
E.g., my map might have the strings:
"AK", "Alaska"
"CA", "California"
"NY", "New York"
I would want as output:
Alaska, California, and New York
for English and
Alaska, California, y New York
for Spanish.
So I have:
public static String getHumanReadableStates(Map<String, String> stateMap) {
long count = stateMap.values().stream().map(Object::toString).count();
return stateMap.values().stream().map(Object::toString)
.limit(count - 1)
.collect(Collectors.joining(", "))
.concat(", ")
.concat(LocaleUtil.getBundleValue("theWordAnd"))
.concat(" ")
.concat(Objects.requireNonNull(stateMap.values().stream().reduce((first, second) -> second)
.orElse(null)));
}
where LocaleUtil
has a method called getBundleValue()
to simply get the word "and" from messages.properties
.
Is there a simpler way to achieve this? Or should streams be avoided altogether?