Sorting set of string numbers in java

前端 未结 5 1161
别那么骄傲
别那么骄傲 2021-01-24 08:05

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,

5条回答
  •  天命终不由人
    2021-01-24 08:12

    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() {
    
            @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

提交回复
热议问题