是否有一个 Java 库可以从数字列表中创建一个数字范围? [英] Is there a Java library that will create a number range from a list of numbers?

查看:46
本文介绍了是否有一个 Java 库可以从数字列表中创建一个数字范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a table of contents, and what I have is a Map of product numbers to pages. So an entry might look like this:

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

我当然可以编写代码,但我认为其他人已经解决了这个问题.我的谷歌搜索一无所获.

I can code this of course, but I figured that someone else has already solved this problem. My Googling has yielded naught.

一如既往地感谢您提供的任何帮助!

I appreciate any help you can offer, as always!

推荐答案

您可以将数字收集到一个有序集合中,然后迭代这些数字.

You could collect the numbers into a sorted set and then iterate over the numbers.

快速而肮脏的例子:

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 库可以从数字列表中创建一个数字范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆