user4316384
user4316384

Reputation:

Sorting an ArrayList in Java with Strings and Integers

I have an ArrayList of Strings in Java. All strings have the format [Integer] [String]. For example:

100 Tom Dsa 23 John Asdf
98 Mary Qwerty

I want to sort this ArrayList by the Integer. The correct output would be:

23 John Asdf 98 Mary Qwerty 100 Tom Dsa

Right now, I'm using the following code:

Collections.sort(obj);

The problem with it is that interprets the integer as a string, therefore 100 is sorted before 2.

Is there any way of sorting this correctly?

Upvotes: 0

Views: 148

Answers (3)

rev_dihazum
rev_dihazum

Reputation: 818

One approach: You could write a custom Comparator which scan int value from String using java.util.Scanner and compare them as bellow:

Collections.sort(obj, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return new Scanner(s1).nextInt() - new Scanner(s2).nextInt();
    }
});

EDIT: it is safe to use Scanner to parse Integer when there may be few leading space exists as bellow:

" 98 Mary Qwerty"

instead of "98 Mary Qwerty"

Upvotes: 1

VishalZ
VishalZ

Reputation: 31

    Map<Integer, String> map = new TreeMap<Integer, String>();
    for (String string : obj) {
        String key = string.substring(0, string.indexOf(" "));
        map.put(Integer.valueOf(key),
                string.substring(key.length(), string.length()));
    }
    obj.clear();
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
        obj.add(entry.getKey().toString()+entry.getValue());
    }
    System.out.println(obj);

OUTPUT::

[23 John Asdf, 98 Mary Qwerty, 100 Tom Dsa]

Upvotes: 0

Saravana
Saravana

Reputation: 12817

If the elements in the List always be like Integer and String delimited by space you can use below

    Collections.sort(obj, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return Integer.parseInt(s1.split("\\s+")[0]) -  Integer.parseInt(s2.split("\\s+")[0]);

        }
    });

Upvotes: 2

Related Questions