I'm looking for a clever way to do the following operation:
Take a list of numbers:
1, 2, 3, 4, 5, 12, 13, 14, 19
and compact it into a string like so:
1-5, 12-14, 19
With the following rule: only compress into a range (i.e. use a dash) when the count of numbers in the range is 3 or more.
I.e.: 1, 2, 4, 5 would result in: 1, 2, 4, 5 and NOT: 1-2, 4-5
Now that we have seen several Stream variants, here the non-Stream variant for comparison:
private static StringBuilder appendRange(StringBuilder sb, int start, int previous) {
sb.append(start);
if(start!=previous) sb.append(previous-start>1? " - ": ", ").append(previous);
return sb;
}
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 12, 13, 14, 19);
StringBuilder sb = new StringBuilder();
int previous = list.get(0), start = previous;
for(int next: list.subList(1, list.size())) {
if(previous+1 != next) {
appendRange(sb, start, previous).append(", ");
start = next;
}
previous = next;
}
String result = appendRange(sb, start, previous).toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With