Ozymandias
Ozymandias

Reputation: 166

Sorting by strings

I'm trying to implement quick sort to sort a list of string values that are all numeric.

it looks like ["1","2","3","4","5"] and so on

I'm using the following code to compare elements

public class TypeComparator<E> implements Comparator<E> {
    @Override
    public int compare(E a, E b) {
        return ((Comparable<E>) a).compareTo(b);
    }
}

My sorted list, however returns values in this order

First 5:
1 10 100 1000 10000 
Last 5:
99995 99996 99997 99998 99999 

The first 5 values are obviously wrong, and the last 5 values should be 99996-100000

With integer values the sort works correctly, but with strings I believe I'm not comparing them correctly.

Upvotes: 0

Views: 74

Answers (2)

agilob
agilob

Reputation: 6223

There is no need to implement a comparator for Integer class. Integer class already implements Comparable interface and has compareTo method. That means you can sort classes like Integer, Long, BigDecimal using only TreeSet:

List<String> strings = new ArrayList<>(Arrays.asList("1", "2", "10", "5"));
Set<Integer> sorted = new TreeSet<>();
for(String s : strings) {
   sorted.add(Integer.valueOf(s));
}
sorted.forEach(el -> System.out.println(el));

That solution is not really what you're after, as it returns a collection of sorted Integers not Strings, but worth to keep that in mind in the future.

Upvotes: 0

Bogdan Lukiyanchuk
Bogdan Lukiyanchuk

Reputation: 767

    List<String> strings = new ArrayList<>(Arrays.asList("1", "2", "10", "5"));
    strings.sort(Comparator.comparing(Integer::parseInt));

Possible will be faster for big arrays

    List<String> sorted = strings.stream()
            .mapToInt(Integer::parseInt)
            .sorted()
            .mapToObj(String::valueOf)
            .collect(Collectors.toList());

Upvotes: 2

Related Questions