按字母顺序排序<player> ArrayList名称

时间:2016-11-06 12:07:11

标签: java sorting arraylist

/* Parent */
.wrapper {
  display: table;
}

/* Child */
.indexWelcome {
  display: table-cell;
}

我一直在努力尝试,但由于您无法将/** * Sorts the list of players alphabetically by name. * Adapt insertion sort algorithm. * You can assume that no two players have the same name. * Question T1. Adapting insertion sort for this method * could yield efficiencies relative to some other approaches * for some important special cases. * Do you agree and if so why? Write about 6 to 10 lines. */ public void alphabeticSort() { Player temp; for (int i = 0; i < players.size(); i++) { for (int j = players.size() - 1; j > i; j--) if (players.get(i).compareTo(players.get(j)) < 0) { temp = players.get(i); players.set(i, players.get(j)); players.set(j, temp); } } } <>班级{{1}一起使用,我在尝试比较时遇到了一些困难}。我们也无法使用任何<Player>次导入。

向正确的方向推进会很棒!

2 个答案:

答案 0 :(得分:2)

如果您想按名称比较玩家,请按名称比较对象:

if (players.get(i).getName().compareTo(players.get(j).getName()) < 0) {

如果您被允许使用Collections.sort,那么实施可能会更简单,更好:

public void alphabeticSort() {
    Collections.sort(players, (p1, p2) -> p1.getName().compareTo(p2.getName()));
}

答案 1 :(得分:1)

您可以使用Java 8 Lambda按字母顺序按名称排序。它会更简洁。

以下面的代码为例 -

public class Test {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>(Arrays.asList(new Person("seal", 25), new Person("tomcat", 32)
                , new Person("Alpha", 15)));

        // using Java 8 lambda to sort
        // you could use this portion inside your alphabeticSort() method.
        List<Person> newList = list.stream()
                .sorted(Comparator.comparing(i -> i.getName()))
                .collect(Collectors.toList());

        // for printing
        newList.stream()
                .forEach(System.out::println);

    }

    static class Person {
        String name;
        int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

所以你的``方法看起来可能会返回一个基于name-

的排序列表
public List<Person> alphabeticSort(List<Person> list) {
    return list.stream()
            .sorted(Comparator.comparing(i -> i.getName()))
            .collect(Collectors.toList());
}