简体   繁体   中英

Using comparator without adding class

I am trying to sort an arraylist by string length, i know of implementing Comparator, but i was wondering if this could be done within my function, without adding any extra classes or methods? Ideally I want to output them shortest to longest, but that I can do!

Here is a snippet of the method i would like to implement the comparator with.

public static void sCompare(BufferedReader r, PrintWriter w) throws IOException {

    ArrayList<String> s= new ArrayList<String>();

    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
        s.add(line);
        n++;
    }
    //Collections.sort(s);  

    Iterator<String> i = s.iterator();
    while (i.hasNext()) {
        w.println(i.next());
    }
  }

Thanks in advance for any input!

I don't see anything wrong with implementing the Comparator interface. If your only concern is doing everything in the function, you could use an anonymous implementation. Something along the lines of :

    Collections.sort(s, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.length() - o2.length();
        }
    });  

(that would replace you current line //Collections.sort(s); )

PS : you never use the value of n .

PPS: You may have to invert o1 and o2 depending of the order you want in the return statement.

Another example of implementing an interface with an anonymous class

I'm going to assume by "class" you mean "top level class", thus allowing the use of an anonymous class :

Collections.sort(s, new Comparator<String>() {
    public int compare(String a, String b) {
        // java 1.7:
        return Integer.compare(a.length(), b.length());
        // java 1.6
        return a.length() - b.length();
    }
});

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