Home > Back-end >  How to custom sort a list in Java
How to custom sort a list in Java

Time:11-14

Lets say I have a list called numbersList contains these elements: [ 101, 102, . . 196, 201, 202, . . 296, 301, 302, . . 396, . . 15601, 15602, . . 15696 ]

I want to sort it so that it becomes something like this: [ 101, 201, 301, 15601, 102, 202, 302, 15602, . . 196, 296, 396, 15696 ]

Note that each group will always end on the 96th number. that means i will always have from x01 to x96 where x is a long value.

I tried to use some loop statements to do it but i couldn't get anywhere because i don't know how many group i will have in the list, that is why i couldn't find a suitable loop for it.

This is my failed attempt :(

for (int i = 0 ; i < numbersList.size() ; i = i   groups-1) {
    numbersList2.add(numbersList.get(i));
    for (int j = 0 ; j == groups - 1; j  ) {
        int k = i   96;
        numbersList2.add(numbersList.get(k));
    }
}

The group variable tells me how many groups will the user input.

CodePudding user response:

This may help:

List<Integer> list = Arrays.asList(101, 102, 103, 201, 202, 203, 295, 296, 301, 302, 303, 304, 396);
list.sort((o1, o2) -> {
    int v1 = o1 % 100;
    int v2 = o2 % 100;
    if (v1 < v2) {
        return -1;
    } else if (v1 == v2) {
        return o1.compareTo(o2);
    } else {
        return 1;
    }
});
System.out.println(Arrays.toString(list.toArray()));

Gives:

[101, 201, 301, 102, 202, 302, 103, 203, 303, 304, 295, 296, 396]

CodePudding user response:

The cleanest answer is using Comparator interface, you should create a class implementing this interface and implement compare method.

Example:

class People {
    int id;
    String name,
    String address;

    ...
}
  
class SortById implements Comparator<People> {
    public int compare(People a, People b) {
        return a.id - b.id;
    }
}
  
class SortByName implements Comparator<People> {
    // Used for sorting in ascending order
    public int compare(People a, People b) {
        return a.name.compareTo(b.name);
    }
}

And then:

    ArrayList<People> arr = new ArrayList<People>();
    arr.add(new People(111, "bbbb", "London"));
    arr.add(new People(131, "aaaa", "Montevideo"));
    arr.add(new People(121, "cccc", "Zaragoza"));
  
    Collections.sort(arr, new SortById());

    //Or...

    Collections.sort(arr, new SortByName());

It's highly reusable.

  • Related