如何对 java 中的原始数据进行排序

How to sort raw data in java

我有以下类型的数据。

[4.2.5, 4.1.3.2.4, 4.1.2.1.28, 4.1.2.1.18, 1.2.18.1.3, 7.2.4, 1.2.15.2.2,  
4.1.4.6, 9, 4.1.2.3.7, 2.1.4, 2.3.14, 1.12.1, 1.2.1, 4.1.2.1.35, 4.2.3,  
2.1.8.3, 4.1.2.3.10, 3.3.9, 1.7.5, 2.1.9.2.1, 1.1.11, 8.3.2, 2.2.3.2,   
4.1.2.1.9, 4.1.3.3.1, 2.1.9.2.11, 1.6.4.1, 2.2.1.2, 2.1.17.4, 1.2.16, 8.3.1,   
4.1.2.4.11, 1.6.3.1, 1.9.2, 6.10, 1.1.24.8.1, 2.1.1.1, 1.10.1, 1.2.18.4.1.1,   
7.3.37, 3.2.17, 1.1.10, 7.3.28, 5.2.1, 1.4.5.5, 1.7.3.1, 4.1.2.1.13, 7.3.26,   
1.2.18.5.1, 1.4.2.7, 4.1.2.2.4, 1.3.2.4, 1.1.20.3, 1.13.2, 1.1.17.2, 2.2.2.6,   
3.4.3, 1.2.18.10, 1.2.6.2, 3.2.23, 2.1.7.1.3, 4.1.3.3.2, 2.1.3.4, 7.2.3,   
1.4.5.8, 1.1.2, 8.1.5, 1.2.9, 2.3.12, 6.8, 4.1.2.1.21, 2.1.5.2.3, 1.1.22.3,   
4.1.3.2, 7.1, 4.1.4.9, 1.7.7, 8.2.2, 2.1.5.1.5, 1.1.24.5, 1.2, 4.1.2.1.11,  
2.3.1, 3.3.10, 1.6.3.6, 1.5.9, 1.2.18.5, 6, 4.1.2.4, 1.2.18.2.3, 1.4.2.6,   
1.5.11, 2.1.1.2, 1.1.24.7.3, 1.2.13, 4.1.3.2.2, 5.1.2, 2.1.5.3, 6.3,   
4.1.3.3.7.1, 1.7, 1.2.18.11, 3.3.7, 8.2.14, 4.1.2.3.15, 2.1.8.1, 1.1.20, 7.3.24,   
1.13.11, 2.1.2.7, 3, 2.3.3, 1.1.3, 4.1.3.3.4, 2.1.9, 8.2.8, 2.2.2.16, 1.6.3.12,   
2.2.1.5, 1.9.1, 4.1.2.3.6, 1.6.3, 1.3.2.2, 1.10, 7.4, 4.1.2.1.24, 5.1.9,   
2.1.3.1, 1.1.9, 1.6.3.8, 2.3.9, 2.1.7.1.4, 7.3.1, 8.1, 2.3.14.1, 1.5.10,   
2.1.13.1, 1.2.18.2.1.1, 1.4.2, 1.1.24.3, 2.1.11, 1.1.24.4, 7.3.42.8, 1.1.22,   
1.5.16, 4.1.2.1.4, 1.3.2.1, 2.1.3.2, 1.4.5.7.2, 2.3.10, 4.1.2.1.16, 1.9.3,  
1.8.2, 6.9, 2.2.2.21, 2.1.3.7, 4.1.2.1.32, 2.1.9.2.4]   

我需要使用 Comparator 对它进行排序,例如

1   
1.1   
1.1.2  
1.1.2.2  
1.2.3
1.5
4.0.1  

我无法决定我必须使用哪种数据类型,"String" 数据类型还是什么?以及如何排序。

使用 String 和默认 Comparator

您的数据将按字典顺序排序,这似乎符合您想要的排序顺序。

示例

List<String> test = new ArrayList<String>();
// added in "random" order
test.add("1.2.3");
test.add("1.5");
test.add("4.0.1");
test.add("1.1");
test.add("1.1.2");
test.add("1.1.2.2");
// no Comparator given as second argument ==> 
// default comparator for String, which is lexicographical
Collections.sort(test);
System.out.println(test);

输出

[1.1, 1.1.2, 1.1.2.2, 1.2.3, 1.5, 4.0.1]

备注

如果您需要删除重复项,请使用 ankur-singhal 的技巧。

现在

一些Java8魔法。

Number[] test = {1.122, 1.12, 1.1, 1.23, 1.5, 4.01, 1};
List<String> converted = Arrays
    .stream(test)
    .map((n) -> 
        String.valueOf(n)
    )
    .sorted()
    .collect(Collectors.toList());
System.out.println(converted);

输出

[1, 1.1, 1.12, 1.122, 1.23, 1.5, 4.01]

也可以使用TreeSet(TreeSet是SortedSet的一个实现),以String为key进行排序。 这将不允许添加重复项

public static void main(String[] args) throws Exception {
        Set<String> test = new TreeSet<String>();
        test.add("1.2.3");
        test.add("1.5");
        test.add("4.0.1");
        test.add("1.1");
        test.add("1.1.2");
        test.add("1.1.2.2");
        System.out.println(test);
    }

输出

[1.1, 1.1.2, 1.1.2.2, 1.2.3, 1.5, 4.0.1]