Sorting set of string numbers in java

2020-04-20 02:27发布

问题:

I need to sort a Set of String's which holds number.Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8]. I need to sort it to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. But when i use Collections.sort(keyList); where keyList is Set, the reult i obtained is [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]. Please help.

回答1:

Write a custom comparator and parse it as argument to Collections.sort(Collection,Comparator). One solution is parsing your Strings to Integers.

    Collections.sort(keyList, new Comparator<String>()
    {
        @Override
        public int compare(String s1, String s2)
        {
            Integer val1 = Integer.parseInt(s1);
            Integer val2 = Integer.parseInt(s2);
            return val1.compareTo(val2);
        }
    });


回答2:

can you try with:

final int[] searchList =
        new int[] { 15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8 };
Arrays.sort(searchList);

The result is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

The list needs to be int



回答3:

Your Strings will be sorted as Strings in natural order, and not as numbers. So, "11" comes after "10" and "2" will come after "11111111110".

What to do?.

Use Integer.parseInt() to parse each String value in the set as integer, then add them to a set and call Collections.sort().



回答4:

Transform the Strings into Integers first.

List<Integer> ints = new ArrayList<>();
for (String s : strings)
    ints.add(Integer.parseInt(s));
Collections.sort(ints);

If you don't require duplicate values, you can use a SortedSet, which maintains the order automatically:

SortedSet<Integer> ints = new TreeSet<>();
for (String s : strings)
    ints.add(Integer.parseInt(s));
// all done!


回答5:

you could do as Kai said, and convert your String to integer and compare it

but it is expensive operation,what i suggest is this :

 keyList.sort(new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            if (o1.length() == o2.length()){
                return o1.compareTo(o2);
            }
            return o1.length() - o2.length();
        }
    });

if your numbers has same length, then compare them by using String.compareTo, otherwise, sort them by order, so 1 2 3 will be automatically before 11 22 etc