Is there a way I can match this ArrayList so that burger1 get in place 1?

Viewed 78

I want to match the ArrayList so that right Burgare gets the right position for example Burgare6 gets position 6 and Burgare2 gets position 2 and so on.

public static void main(String[] args) {

   List<String> burgare = Arrays.asList("1: Burgare 6", "2: Burgare 7", "3: Burgare 2",
                                        "4: Burgare 1", "5: Burgare 3", "6: Burgare 4", 
                                        "7: Burgare 5");

    System.out.println(burgare);

}
2 Answers

Here you go.

    Comparator<String> lastNumberComparator = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1.split(" ")[2]).compareTo(Integer.valueOf(o2.split(" ")[2]));
        }
    };

    Collections.sort(burgare, lastNumberComparator);
    System.out.println(burgare);

Using String.split(" ") with spaces is a quick way to split your strings into three tokens "4:", "Burgare", "1" where the last token [2] is the value we use to sort.

You can simply use :

Collections.sort(burgare, new Comparator<String>() {
    @Override
    public int compare(String str1, String str2) {
       return Integer.valueOf(str1.split(" ")[2])
                     .compareTo(Integer.valueOf(str2.split(" ")[2]));
    }
});

If you are on java-8 then :

Collections.sort(burgare, (str1, str2) -> 
         Integer.valueOf(str1.split(" ")[2]).compareTo(Integer.valueOf(str2.split(" ")[2])));
Related