簡體   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