数字分段,非连续的数字把连续的部分进行分段处理
记录一个需求
有一批邮编数据 类似于100,101,102,105,108,110
我希望得到这样的结果,如果是连续的我只需要一个其实和结尾 例如上面的数据 我希望得到 100-102 105-105 108-108 110-110
下面是我的实现方式
public List<PostCodeRanges> postRanges(List<String> postCode) {
//剔除重复的数据
HashSet<String> setStrings = new HashSet<>(postCode);
//转为数字
List<Integer> integerList = setStrings.stream().map(Integer::parseInt).collect(Collectors.toList());
//排序
List<Integer> sored = integerList.stream().sorted(Comparator.comparing(item -> item)).collect(Collectors.toList());
int start = 0;
List<PostCodeRanges> postCodeRangesList = new ArrayList<>();
for (int i = 1; i < sored.size(); i++) {
int current = sored.get(i);
int last = sored.get(i - 1);
if (current - last > 1) {
Integer s = sored.get(start);
Integer e = sored.get(i - 1);
postCodeRangesList.add(new PostCodeRanges(String.valueOf(s), String.valueOf(e)));
start = i;
}
if (i == sored.size() - 1) {
Integer s = sored.get(start);
Integer e = sored.get(i);
postCodeRangesList.add(new PostCodeRanges(String.valueOf(s), String.valueOf(e)));
}
}
return postCodeRangesList;
}
结果对象
@Data
@AllArgsConstructor
public class PostCodeRanges {
/**
* 开始
*/
private String start;
/**
* 结尾
*/
private String end;
}
展示结果
输入:
[
"100",
"101",
"102",
"105",
"108",
"110"
]
输出:
[
{
"start": "100",
"end": "102"
},
{
"start": "105",
"end": "105"
},
{
"start": "108",
"end": "108"
},
{
"start": "110",
"end": "110"
}
]