Home > Mobile >  How to sort array list contains list as elements based on custom required order
How to sort array list contains list as elements based on custom required order

Time:11-01

I have an arraylist which is like
List<List<Integer>> res = new ArrayList();
After some process my res arraylist will be containing
[1, 1, 2]
[1, 1]
[1, 2]
[1]
[2]
These elements but i want sorted order which looks like
[1]
[1 1]
[1 1 2]
[1 2]
[2]

so what i have done is

   Collections.sort(res,new Comparator<List<Integer>>(){
        public int compare(List<Integer> o,List<Integer> s){
            int c=0;
            //c=o.size().compareTo(s.size());
            //if(c==0){
                for(int i=0;i<Math.min(s.size(),o.size());i  ){
                    c=o.get(i).compareTo(s.get(i));
                    if(c!=0) return c;
                }
           //}
        
            return c;
        }    
    });

But it is not working

CodePudding user response:

Try comparing the sizes of the lists instead of just returning c at the end of compare:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Main {

    public static void main(String[] args) {
        List<List<Integer>> list = new ArrayList<>();
        list.add(new ArrayList<>(Arrays.asList(1, 1, 2)));
        list.add(new ArrayList<>(Arrays.asList(1, 1)));
        list.add(new ArrayList<>(Arrays.asList(1, 2)));
        list.add(new ArrayList<>(Arrays.asList(1)));
        list.add(new ArrayList<>(Arrays.asList(2)));
        
        System.out.printf("Before: %s%n", list);
        
        Collections.sort(list, new Comparator<List<Integer>>() {
            public int compare(List<Integer> o, List<Integer> s) {
                for (int i = 0; i < Math.min(o.size(), s.size()); i  ) {
                    int c = o.get(i).compareTo(s.get(i));
                    if (c != 0) {
                        return c;
                    }
                }
                return Integer.compare(o.size(), s.size());
            }
        });
        
        System.out.printf("After: %s%n", list);
    }

}

Output:

Before: [[1, 1, 2], [1, 1], [1, 2], [1], [2]]
After: [[1], [1, 1], [1, 1, 2], [1, 2], [2]]
  • Related