是否有一个Java库会根据数字列表创建数字范围? - java

我正在创建目录,而我所拥有的是产品编号映射到页面。因此,条目可能如下所示:

ABC123 => [59, 58, 57, 19, 36, 15, 33, 34, 13, 39, 11, 37, 38, 21, 20, 40, 63, 60, 45, 46, 22, 23, 24, 26, 3, 2, 10, 1, 7, 6, 5, 4, 8]

我想从中得到的是:

1-8,10,11,13,15,19-24,26,33,34,36-38,40,45,46,57-60

我当然可以编写代码,但是我发现其他人已经解决了这个问题。我的谷歌搜索无济于事。

一如既往,我感谢您能提供的任何帮助!

参考方案

您可以将数字收集到一个排序集中,然后遍历这些数字。

快速而肮脏的例子:

SortedSet<Integer> numbers = new TreeSet<Integer>();

numbers.add( 1 );
numbers.add( 2 );
numbers.add( 3 );
numbers.add( 6 );
numbers.add( 7 );
numbers.add( 10 );

Integer start = null;
Integer end = null;

for( Integer num : numbers ) {
  //initialize
  if( start == null || end == null ) {
    start = num;
    end = num;
  }
  //next number in range
  else if( end.equals( num - 1 ) ) {
    end = num;
  }
  //there's a gap
  else  {
    //range length 1
    if( start.equals( end )) {
      System.out.print(start + ",");
    }
    //range length 2
    else if ( start.equals( end - 1 )) {
      System.out.print(start + "," + end + ",");
    }
    //range lenth 2+
    else {
      System.out.print(start + "-" + end + ",");
    }

    start = num;
    end = num;
  }
}

if( start.equals( end )) {
  System.out.print(start);
}
else if ( start.equals( end - 1 )) {
  System.out.print(start + "," + end );
}
else {
  System.out.print(start + "-" + end);
}

产量:1-3,6,7,10

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java:BigInteger,如何通过OutputStream编写它 - java

我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

Java:从类中查找项目名称 - java

仅通过类的实例,如何使用Java反射或类似方法查找项目名称?如果不是,项目名称(我真正想要的是)可以找到程序包名称吗? 参考方案 项目只是IDE使用的简单组织工具,因此项目名称不是类或JVM中包含的信息。要获取软件包,请使用Class#getPackage()。然后,可以调用Package#getName()将包作为您在代码的包声明中看到的String来获取…

Java:“自动装配”继承与依赖注入 - java

Improve this question 我通常以常见的简单形式使用Spring框架: 控制器服务存储库通常,我会在CommonService类中放一个通用服务,并使所有其他服务扩展到类中。一个开发人员告诉我,最好在每个服务中插入CommonClass而不是使用继承。我的问题是,有一个方法比另一个更好吗? JVM或性能是否会受到另一个影响?更新资料Comm…