按特定顺序对数据进行排序 [英] sorting data in specific order

查看:83
本文介绍了按特定顺序对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我的 rowId 如下所示

Here my rowId's are like the below

1

1.1

1.2

.

1.9

2

2.1

.

.3..9

.

9.9

10

10.1

List<MyBean> sortedList = rootItems.stream().sorted(Comparator.comparing(MyBean::getRowId)) .collect(Collectors.toList());

通过使用上面的代码,我得到如下输出.

By using the above code I am getting the output like below.

1

10

11

12

2

2.1

2.2

.

.

但我想要像下面这样的输出

but I want output like the below

1

1.1

1.1.1

1.1.1.1

1.2

1.3

.

.

.

1.9

10

11

.

2

2.1

2.2

2.3

.

.

3

3.1

3.2

.

.

4

.

.

.

9

9.1

9.2

.

.

9.9

10

10.1

.

.

这样就需要继续了

如果我想要这个,我需要使用哪个 Set

If I want like this which Set I need to use

推荐答案

如果您在内部将这些字符串标准化为可以排序的格式,则比较这些字符串会容易得多.我建议用零填充各个项目,如下所示:

Comparing these strings would be a lot easier if you normalized them internally, to a format that can then be sorted. I'd suggest to pad the individual items with zeroes, something like this:

private static final Pattern SINGLE_DIGIT = Pattern.compile("\\b(\\d)\\b");
...
String padWithZeroes = SINGLE_DIGIT.matcher(yourInputString).replaceAll("0$1");

现在只需对填充的字符串进行排序.这是假设最高的数字是2位数,如果不是,我们需要调整正则表达式,逻辑会稍微复杂一些.

now just sort on the padded strings. This is assuming that the highest number will be 2 digits, if not, we will need to adjust the regex and the logic will be slightly more complicated.

如果任何数字段的长度可以超过 2 位,那么它会变得更加复杂.这是一种将所有段填充到最大长度的方法:

If any of the numeric segments can be longer than 2 digits, then it will get more complicated. Here's a method that pads all segments to the maximum length:

static String padWithZeroes(String yourInputString, int digits) {
    final Matcher matcher = SINGLE_DIGIT.matcher(yourInputString);
    StringBuffer sb = new StringBuffer();
    while(matcher.find()){

        matcher.appendReplacement(sb, pad(digits - matcher.group().length())+matcher.group());
    }
    matcher.appendTail(sb);
    return sb.toString();
}

static String pad(int length) {
    final char[] chars = new char[length];
    Arrays.fill(chars, '0');
    return new String(chars);
}

这里的问题是您必须预先知道 digits 参数的值,因此您要么知道数据,要么必须进行单独的迭代来测量最大长度.

The problem here is that you will have to know the value of the digits parameter up front, so either you know your data, or you will have to do a separate iteration in which you measure the max length.

这篇关于按特定顺序对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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