I have an arraylist of arraylist, each inner arraylist contains 2 values, the first is an integer and the second is a string so essentially it would look like: {5, some text}, {12, some more text}, {3, even more text} etc, what I would like to do is take this and sort it so its in descending order of the largest integer to smallest, so the previous example then looks like: {12, some more text}, {5, some text}, {3, even more text}, any help would go a long way thanks in advance
2 Answers
your data structure sounds like it is a 'Map' actually. Maybe you should look into data structures, and collection interfaces and classes in particular...
If you still think that what you have is a 'List', then you should make a Collections.sort operation with right kind of Comparator or Comparable
Here is a solution to your data structure if the List is the right one;
import java.util.ArrayList;
import java.util.Collections;
public class InnerObject implements Comparable<InnerObject> {
Integer index;
String name;
public InnerObject(Integer index, String name) {
this.index = index;
this.name = name;
}
@Override
public int compareTo(InnerObject other) {
return index.compareTo(other.index);
}
@Override
public String toString() {
return "{" + index + "," + name + "}";
}
public static void main(String[] args) {
ArrayList<InnerObject> list = new ArrayList<InnerObject>();
list.add(new InnerObject(666, "devil"));
list.add(new InnerObject(1, "one"));
list.add(new InnerObject(10, "ten"));
System.out.println("list before order: " + list);
Collections.sort(list);
System.out.println("list after order: " + list);
}
}
7 Comments
Korgen
I totally agree with this. It looks more of a map than a list of lists... have a look at Java's Treemap, a map ordered by keys: docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
Edmund Rojas
This seems to be exactly what I need, only 2 things I need to figure out now is how to reverse the list so it returns in biggest to smallest and how do I get the second value back out?
lithium
in the compareTo method, if you write 'return other.index.compareTo(index);' then the order is reversed... Check for null conditions somewhere though, either in compareTo or somewhere up in the logic...
Edmund Rojas
oh no, it appears that the sort function actually didnt sort the numbers in order, they still wind up just staying in the same order they went in
lithium
are you sure? coz it should be as follows; ' - list before order: [{666,devil}, {1,one}, {10,ten}] - list after order: [{1,one}, {10,ten}, {666,devil}] '
|
ArrayLists, instead of a separate class?ArrayListhere is awkward, weakly typed, and using a new class for it would make the sorting part significantly easier.Comparablebased on the integer key.