Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact a comma delimited number list into ranges

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

like image 510
amran_bd Avatar asked Jul 26 '17 08:07

amran_bd


1 Answers

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();
like image 69
Holger Avatar answered Oct 19 '22 03:10

Holger