简体   繁体   中英

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

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

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM