0

我想将输入作为名字和姓氏。之后,将根据姓氏进行排序并显示名字和姓氏。. 例如。

输入:-

John smith 
Albert kennedy
John dsouza

输出

John dsouza
Albert kennedy
John smith
4

6 回答 6

1

您需要创建自己的ComparatorList根据给定的Comparator. 这是演示:

import java.util.*;
class  SortLastName
{
    public static void main(String[] args) 
    {
        List<String> list= new ArrayList<String>();
        list.add("John smith");
        list.add("Albert kennedy");
        list.add("John dsouza");
        System.out.println("Before sorting :"+list);
        Collections.sort(list,new myComparator());
        System.out.println("After sorting :"+list);
    }
    static class myComparator implements Comparator<String>
    {
        public int compare(String str1,String str2)
        {
            String[] tokens1 = str1.split("\\s+");
            String[] tokens2 = str2.split("\\s+");
            int i = tokens1[1].compareTo(tokens2[1]);
            return i;
        }
    }
}
于 2013-03-25T15:25:34.013 回答
0

您可以使用自定义字符串比较器来实现此目的:

public class LastNameComparator implements Comparator<String>{

    public int compare(String object1, String object2) {

        String name1 = object1.split("\\s+")[1].toUpperCase();
        String name2 =  object1.split("\\s+")[1].toUpperCase();

        return name1.compareTo(name2);

    }

}

然后使用Collections排序方法

Collections.sort(namesList, new LastNameComparator());

请注意,您需要确保您的输入匹配:“FirstName LastName”格式以避免任何ArrayOutofBoundException,如果名称没有空格,或者如果名称有多个部分,则会出现意外结果。

于 2013-03-25T15:07:31.333 回答
0
String[] names = { "John smith", "Albert kennedy", "John dsouza" };
Arrays.sort(names, new Comparator<String>() {

    @Override
    public int compare(String firstName, String lastName) {
        return firstName.split("\\s+")[1].compareTo(lastName.split("\\s+")[1]);
    }

});
System.out.println(Arrays.toString(names));

或创建一个为您执行此操作的方法,如下所示

private static Object[] sortLastName(Object[] a) {
    Object[] temp = new Object[a.length];

    for (int i = 0; i < temp.length - 1; i++) {
        if (a[i].toString().split("\\s+")[1].compareTo(a[i + 1].toString()                  .split("\\s+")[1]) < 0) {
            temp[i] = a[i];
            temp[i + 1] = a[i + 1];
        }
     }

    return temp;
}
于 2013-03-25T16:01:09.917 回答
0
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author pramod
 */
public class SortNames {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    String name1 = "John Smith";
    String name2 = "Albert kennedy";
    String name3 = "John dsouza";
    String name4 = "John Dsouza";
    String name5 = "Mark Smith";
    String name6 = "john Kennedy";

    ArrayList<String> inputStringList = new ArrayList<String>();
    inputStringList.add(name1);
    inputStringList.add(name2);
    inputStringList.add(name3);
    inputStringList.add(name4);
    inputStringList.add(name5);
    inputStringList.add(name6);
    System.out.println(inputStringList);
    System.out.println("\n\n\n");
    ArrayList<Name> nameList = sortByLastNames(inputStringList);
    System.out.println(nameList);


}

public static class Name implements Comparator<Name> {

    String fname;
    String lname;

    public Name() {
    }

    public Name(String fname, String lname) {
        this.fname = fname;
        this.lname = lname;
    }

    @Override
    public String toString() {
        return fname + " " + lname;
    }
    /*
     * Writing custom comparator to compare both the names. Code will
     * compare based on last name and then first name (ignores cases).
     */

    @Override
    public int compare(Name o1, Name o2) {
        return o1.lname.compareToIgnoreCase(o2.lname) != 0
                ? o1.lname.compareToIgnoreCase(o2.lname)
                : o1.fname.compareToIgnoreCase(o2.fname);
    }
}

/**
 * Code will split based on the first space.
 * Uses trim to remove the leading and ending spaces. Then,
 * Considers the string before first space as fname and string after first space as lname.
 * @param inputStringList - ArrayList<String> - input list of Strings that
 * needs to be sorted as names
 * @return - ArrayList<Name> - output List of Names that are sorted.
 */
public static ArrayList<Name> sortByLastNames(ArrayList<String> inputStringList) {
    if (inputStringList == null) {
        return null;
    }
    ArrayList<Name> nameList = new ArrayList<Name>();
    for (String fullName : inputStringList) {
        if (fullName != null && fullName.trim().equalsIgnoreCase("")) {
            int firstSpace = fullName.trim().indexOf(' ');
            String fname = "";
            String lname = "";
            if (firstSpace != -1) {
                fname = fullName.substring(0, firstSpace).trim();
                lname = fullName.substring(firstSpace, fullName.length()).trim();
            } else {
                fname = fullName;
                lname = "";
            }
            Name name = new Name(fname, lname);
            nameList.add(name);
        }
    }
    Collections.sort(nameList, new Name());
    return nameList;
}

}

于 2013-03-25T16:03:48.393 回答
0

Try looking into these, they should help

String Split http://javarevisited.blogspot.co.uk/2011/09/string-split-example-in-java-tutorial.html

Collections Sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html

于 2013-03-25T15:02:16.597 回答
0

实现你自己的Comparator,并使用Collections.sort()

于 2013-03-25T15:04:33.813 回答