简体   繁体   English

在Java中按单词的索引号对字符串进行排序(数字作为参数给出)

[英]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? 是否可以通过参数将另一个单词的索引号提供给Comparator?

Not through an argument (parameter) to Comparator , no, but you can either: 不通过Comparator参数(参数) ,否,但是您可以:

  1. Make it a field of your Comparator concrete class, or 使它成为您的Comparator具体课程的一个领域,或

  2. If you implement Comparator as an anonymous class it can be a final variable or parameter the implementation closes over 如果将Comparator实现为匿名类,则它可以是final变量或参数,实现将关闭

#1 is fairly trivial. #1相当琐碎。 Here's an example of #2 ( live copy ): 这是#2( 实时复制 )的示例:

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 ... Java是一种非常灵活的语言,因此您始终可以实现比较器的匿名实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM