按第二个单词对String数组进行排序

时间:2016-10-14 04:22:02

标签: java arrays sorting

我有以下数据

1. John Smith
2. Tom Cruise
3. Chuck Norris
4. Bill Gates
5. Steve Jobs

如您所见,数据采用特定格式[ID]. [Firstname] [Lastname]。有没有办法按Firstname排序这个数组?

输出应该如下所示:

4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise

3 个答案:

答案 0 :(得分:2)

您可以使用lambda传递自己的比较标准。

String[] names = {"1. John Smith", "2. Tom Cruise", "3. Chuck Norris", "4. Bill Gates", "5. Steve Jobs"};

ArrayList<String> namesList = new ArrayList<>();
for(int i=0; i<names.length; i++) {
    namesList.add(names[i]);
}

Collections.sort(namesList, (name1, name2) -> name1.split(" ")[1].compareTo(name2.split(" ")[1]));

for(String name : namesList) {
    System.out.println(name);
}

输出:

4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise

答案 1 :(得分:1)

您可以提供自定义比较器以按名字排序

convert -background none -gravity south out.png -resize 400x200 -extent 400x400 result.png

输出

    List<String> data = Arrays.asList("1. John Smith", "2. Tom Cruise", "3. Chuck Norris", "4. Bill Gates", "5. Steve Jobs");
    Comparator<String> c = (s1, s2) -> s1.split("\\s+")[1].compareTo(s2.split("\\s+")[1]);
    List<String> sorted = data.stream().sorted(c).collect(Collectors.toList());
    System.out.println(sorted);

或只是

[4. Bill Gates, 3. Chuck Norris, 1. John Smith, 5. Steve Jobs, 2. Tom Cruise]

传递给收藏

    Comparator<String> com = Comparator.comparing(s -> s.split("\\s+")[1]);

    Comparator<String> old = new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.split("\\s+")[1].compareTo(s2.split("\\s+")[1]);
        }
    };

答案 2 :(得分:1)

您需要一个自定义比较器

String[] names = new String[]{"1. John Smith","2. Tom Cruise","3. Chuck Norris","4. Bill Gates","5. Steve Jobs"};
List<String> nameList = Arrays.asList(names);
Collections.sort(nameList, new Comparator<String>() {

    @Override
    public int compare(String arg0, String arg1) {
        String firstName0 = arg0.split(". ")[1].split(" ")[0];
        String firstName1 = arg1.split(". ")[1].split(" ")[0];
        return firstName0.compareTo(firstName1);
    }
});

打印:

[4. Bill Gates, 3. Chuck Norris, 1. John Smith, 5. Steve Jobs, 2. Tom Cruise]