-1

I have an ArrayList<ArrayList<String>> that is a list of couple of values:

John, 12.3
Marcus, 35.0
Sue, 11.4

How to sort the list by amount? If in this case there is a better way than using an ArrayList of an ArrayList, please tell me and tell me then how to sort it. Thank you.

rgettman
  • 176,041
  • 30
  • 275
  • 357
smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • http://stackoverflow.com/questions/14475556/how-to-sort-arraylist-of-objects – Sherman Oct 10 '14 at 17:58
  • 1
    It sounds like your inner list of Strings is the ["John", "12.3"] but I can't really tell from your question. You could `Collections.sort(list, comparator)`, where your comparator determines the ordering. – mkobit Oct 10 '14 at 17:58

3 Answers3

3

Instead I will recommend you to use a class and use class like comparable or comparator to sort. Something like this:

class Person implements Comparable<Person> {
    String name;
    double amount;

    Person(String n, double d) {
        name = n;
        amount = d;
    }

    public int compareTo(Person other) {
        if (amount != other.amount)
            return Double.compare(amount, other.amount);
        return name.compareTo(other.name);
    }
}

and this is easy to implement and understand.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
govindpatel
  • 2,539
  • 2
  • 19
  • 20
  • Can you make the same example with ArrayList>? – smartmouse Oct 10 '14 at 18:30
  • 1
    @smartmouse This answer is suggestion to create `List` rather than `List>`. If you don't want to use this suggestion then you will need to write your own `Comparator`, but approach from this answer is preferable. – Pshemo Oct 10 '14 at 18:33
1

Use a Comparator:

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

It'd be great if you could add more information about why you are using those values then I am sure a better approach can be suggested.

An SO User
  • 24,612
  • 35
  • 133
  • 221
0

I solved with this:

    Collections.sort(data, new Comparator<ArrayList<String>>() {
        @Override
        public int compare(ArrayList<String> one, ArrayList<String> two) {
            // Replacements for using Double.parseDouble(string) later
            String value1 = one.get(1).replace(",", ".");
            String value2 = two.get(1).replace(",", ".");

            if (Double.parseDouble(value1) < Double.parseDouble(value2))
            return -1;
        else if (Double.parseDouble(value1) > Double.parseDouble(distanza2))
            return 1;
        else
            return 0;
        }
    });
smartmouse
  • 13,912
  • 34
  • 100
  • 166