简体   繁体   中英

Sort strings by index number of word (the number is given as an argument) in java

For example if I know for certain that I need sort by second word. I can create Comparator like this.

class SecondWordComparator implements Comparator<String>
{
    @Override
    public int compare(String s1, String s2)
    {
        String[] a1 = s1.split(" ");
        String[] a2 = s2.split(" ");

        return a1[1].compareTo(a2[1]);
    }
}

Is it possible to give another index number of word to Comparator through an argument?

Not through an argument (parameter) to Comparator , no, but you can either:

  1. Make it a field of your Comparator concrete class, or

  2. If you implement Comparator as an anonymous class it can be a final variable or parameter the implementation closes over

#1 is fairly trivial. Here's an example of #2 ( live copy ):

import java.util.*;

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String[] strings = new String[] {
            "one two three",
            "uno due tre",
            "uno dos tres",
            "un deux trois"
        };
        sort(strings, 2); // 2 = third word
        for (String s : strings) {
            System.out.println(s);
        }
    }

    private static void sort(String[] strings, final int index) {
        Arrays.sort(strings, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2)
            {
                String[] a1 = s1.split(" ");
                String[] a2 = s2.split(" ");
                String word1 = a1.length > index ? a1[index] : "";
                String word2 = a2.length > index ? a2[index] : "";

                return word1.compareTo(word2);
            }
        });
    }
}

Since you are overriding a method from an interface

@Override
public int compare(String s1, String s2)

then adding a parameter in the method signature violates the declarede method in the interface....

so is not possible...

java is very flexible language so you can always implement anonymous instances of the comparator ...

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