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, 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]
I need to sort this using Comparator like
1
1.1
1.1.2
1.1.2.2
1.2.3
1.5
4.0.1
I am unable to decide which data type I have to use, "String" data type or what? and how to sort it.
Use String and the default Comparator.
Your data will be sorted lexicographically, which seems to fit your desired sort order.
Example
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);
Output
[1.1, 1.1.2, 1.1.2.2, 1.2.3, 1.5, 4.0.1]
Note
Use ankur-singhal's technique if you need to remove duplicates.
And now
Some Java 8 magic.
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);
Output
[1, 1.1, 1.12, 1.122, 1.23, 1.5, 4.01]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With