繁体   English   中英

如何在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和默认的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的技巧。

现在

一些Java 8的魔力。

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进行排序。 这不允许添加重复项

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM