Sorting set of string numbers in java

2020-04-20 02:37发布

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.

5条回答
等我变得足够好
2楼-- · 2020-04-20 02:47

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().

查看更多
ら.Afraid
3楼-- · 2020-04-20 02:50

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

查看更多
再贱就再见
4楼-- · 2020-04-20 02:51

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楼-- · 2020-04-20 03:01

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);
        }
    });
查看更多
干净又极端
6楼-- · 2020-04-20 03:03

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

查看更多
登录 后发表回答