kingsley Dike
kingsley Dike

Reputation: 31

Sort a list by a given criteria

i have a list of strings i want to sort by only the numerical suffix of the string. Below is what i have tried. My desired output is ["ak-2","ss-12","aa-20","pp-90"]

List<String> list1 = new ArrayList<>;
list1.add("aa-20");
list1.add("ss-12");
list1.add("ak-2");
list1.add("pp-90");
Collections.sort(list1);

Upvotes: 0

Views: 62

Answers (1)

Try this ::


        List<String> list1 = new ArrayList<>();
        list1.add("aa-20");
        list1.add("ss-12");
        list1.add("ak-2");
        list1.add("pp-90");

        Comparator<String> comp=new Comparator<String>() {          
            @Override
            public int compare(String o1, String o2) {
                o1=o1.substring(o1.indexOf("-")+1);
                o2=o2.substring(o2.indexOf("-")+1);
                if(Integer.parseInt(o1)>Integer.parseInt(o2)){
                    return 1;
                }
                return -1;
            }
        };

        Collections.sort(list1, comp);
        System.out.println(list1);

Let me know if this helps.

Upvotes: 1

Related Questions