简体   繁体   中英

how to sort arraylist according to “.”?

I created arrayList with this values

 ArrayList<String> list = new ArrayList<>();
 list.add("a.b.c");
 list.add("a.b.d");
 list.add("a.b.e.f");
 list.add("a.b.e.h");

I want to so sorting according to the number of '.'s in the string.

That is, the string that has the minimum number of '.'s will become the first one.

I tried to do this,

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
         return findDot(a) - findDot(b)
    }

    private  findDot(String a ){
         String [] result = a.split("\\.")
         return result .length
    }

});

But it didn't work.

Did I miss something ?

Your source code is wrong(it contains syntax error).

The right code is below:(It works but better code exists)

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.compare(findDot(a), findDot(b));
    }
    private int findDot(String a ){
        String [] result = a.split("\\.");
        return result.length;
    }
});

And I advise you that if you use compare, use Integer.compare(A, B) instead A - B because if A is too big and B is too small(eg -2918291) then A - B is overflow and it raise an error.

private  findDot(String a ){
         String [] result = a.split("\\.")
         return result .length
}

Change it as

private int  findDot(String a){
         String [] result = a.split("\\.");
         return result.length;
}

Works fine for me. The only thing you were missing was a return type for the method findDot and a couple semi-colons, and the space between results .length

import java.util.Collections;
import java.util.Comparator;

public class Hello {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();

         list.add("a.b.e.h");
         list.add("a.b.c");
         list.add("a.b.e.f.h.g");
         list.add("a.b.d");
         list.add("a.b.e.f");


         Collections.sort(list, new Comparator<String>() {
                public int compare(String a, String b) {
                   return findDot(a) - findDot(b);
                }

                 private int findDot(String a ){
                     String [] result = a.split("\\.");
                     return result.length;
                 }

            });

         for (String s : list) {
             System.out.println(s);
         }

    }

}

Output

a.b.c
a.b.d
a.b.e.h
a.b.e.f
a.b.e.f.h.g

If you just want it sorted the other way around, just change this

return findDot(a) - findDot(b);

to this

return findDot(b) - findDot(a);

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