简体   繁体   中英

How to sort an Array List in an order according to our requirement

The List which contains data is in an order of

List<String> list = new ArrayList<String>(); 
list.add('R'); 
list.add('L');
list.add('H');
list.add('A');

If I have to display the list in an order of L,H,R,A.

I tried to add each list value in a LinkedHashMap and and added all in another Linked Hashmap according to the requirement.

Is there any other best way that I can sort this.

You can use java.util.Collections.sort method, pass the array and a comparator:

Collections.sort(list,new Comparator<String>(){

        @Override
        public int compare(String s1, String s2) {
            // write your code to decide the order, return negative value for element that you want to appear before another element, zero for equality. same at compareTo works.
        }

    });

So, if you would like to sort only the LRHA letters, you can do the following (and i assume that any other string will be placed in the end)

        List<String> list = new ArrayList<String>(); 
        list.add('R'); 
        list.add('L');
        list.add('H');
        list.add('A');    

        Collections.sort(list,new Comparator<String>(){

            @Override
            public int compare(String s1, String s2) {
                if(s1 == null)
                    return 2;
                if(s2 == null)
                    return -2;

                if(s1.equals("L")) return -1;
                if(s2.equals("L")) return 1;
                if(s1.equals("H")) return -1;
                if(s2.equals("H")) return 1;
                if(s1.equals("R")) return -1;
                if(s2.equals("R")) return 1;
                if(s1.equals("A")) return -1;
                if(s2.equals("A")) return 1;
                return 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