Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is pretty ugly and verbose in Java, but here is a version. Note, it uses StringUtils from Spring at the very end for the trivial but also ugly process of converting a String collection to a comma delimited string.</p> <p>The key is to use a separate class to model the numeric ranges. Let this class know how to turn itself into a String. Then you won't have so much logic around appending to a StringBuilder.</p> <p>Also, try to think in terms of collections. This always makes things clearer. The pseudo-code is something like: <code>String</code> becomes <code>List&lt;Integer&gt;</code> becomes <code>List&lt;Range&gt;</code> and finally becomes <code>String</code>.</p> <pre><code>public class Ranges { // A class that models a range of integers public static class Range { private int low; private int high; public Range(int low, int high) { this.low = low; this.high = high; } public int getHigh() { return high; } public void setHigh(int high) { this.high = high; } @Override public String toString() { return (low == high) ? String.valueOf(low) : String.format("%d-%d", low, high); } } public static void main(String[] args) { String input = "2,3,6,7,8,10,12,14,15,16"; // Turn input string into a sorted list of integers List&lt;Integer&gt; inputNumbers = new ArrayList&lt;Integer&gt;(); for (String num : input.split(",")) { inputNumbers.add(Integer.parseInt(num)); } Collections.sort(inputNumbers); // Flatten list of integers into a (shorter) list of Ranges Range thisRange = null; // the current range being built List&lt;Range&gt; ranges = new ArrayList&lt;Range&gt;(); for (Integer number : inputNumbers) { if (thisRange != null &amp;&amp; number &lt;= thisRange.getHigh() + 1) { // if we are already building a range (not null) &amp;&amp; this new number is // the old high end of the range + 1, change the high number. thisRange.setHigh(number); } else { // create a new range and add it to the list being built thisRange = new Range(number, number); ranges.add(thisRange); } } // Join List&lt;String&gt; into a single String String result = StringUtils.collectionToCommaDelimitedString(ranges); System.out.println("result = " + result); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload