Java 如何按属性对对象数组列表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2535124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:59:21  来源:igfitidea点击:

How to sort an arraylist of objects by a property?

javasortingcollections

提问by sieve411

Lets say you have an Arraylistof HockeyPlayerobjects.

比方说你有一个ArraylistHockeyPlayer对象。

How could you sort that if they all have a variable int goalsScored. How could you sort them by goalsScored?

如果它们都有一个变量int targetsScored,你怎么能排序?你怎么能按进球数对他们进行排序?

回答by duffymo

Write a custom Comparatorto do the job.

编写一个自定义比较器来完成这项工作。

回答by camickr

Use a generic Comparator like the Bean Comparator.

使用像Bean Comparator这样的通用Comparator

回答by CWF

Java has a set of sort() methods for this sort of thing. See Collections.sort (and Comparable) for details.

Java 有一组 sort() 方法来处理这类事情。有关详细信息,请参阅 Collections.sort(和 Comparable)。

回答by polygenelubricants

You can use Collections.sortwith a custom Comparator<HockeyPlayer>.

您可以使用Collections.sort自定义Comparator<HockeyPlayer>.

    class HockeyPlayer {
        public final int goalsScored;
        // ...
    };

    List<HockeyPlayer> players = // ...

    Collections.sort(players, new Comparator<HockeyPlayer>() {
        @Override public int compare(HockeyPlayer p1, HockeyPlayer p2) {
            return p1.goalsScored - p2.goalsScored; // Ascending
        }

    });

The comparision part can also be written this way :

比较部分也可以这样写:

players.sort(Comparator.comparingInt(HockeyPLayer::goalsScored));

Alternatively, you can make HockeyPlayer implementsComparable<HockeyPlayer>. This defines thenatural ordering for all HockeyPlayerobjects. Using a Comparatoris more flexible in that different implementations can order by name, age, etc.

或者,您可以制作HockeyPlayer implementsComparable<HockeyPlayer>. 这定义所有HockeyPlayer对象自然顺序。使用 aComparator更灵活,因为不同的实现可以按名称、年龄等排序。

See also

也可以看看



For completeness, I should caution that the return o1.f - o2.fcomparison-by-subtraction shortcut must be used with extreme caution due to possible overflows (read: Effective Java 2nd Edition: Item 12: Consider implementing Comparable). Presumably hockey isn't a sport where a player can score goals in the amount that would cause problems =)

为了完整起见,我应该警告说,return o1.f - o2.f由于可能的溢出,必须极其谨慎地使用减法比较快捷方式(阅读:Effective Java 2nd Edition:Item 12:考虑实现Comparable)。大概曲棍球不是一项运动,其中球员可以进球的数量会导致问题=)

See also

也可以看看

回答by user6158055

Just one line with Java 8 :

与 Java 8 仅一行:

Collections.sort(players, (p1, p2) -> p1.getGoalsScored() - p2.getGoalsScored());

回答by Arpit Aggarwal

As @user6158055 suggets, it's one liner with Java 8, as follows:

正如@user6158055 所暗示的那样,它是一个带有 的衬垫Java 8,如下所示:

Collections.sort(
                hockeyPlayerList,
                (player1, player2) -> player1.getGoalsScored()
                        - player2.getGoalsScored());

Complete example to depict the same:

描述相同的完整示例:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<HockeyPlayer> hockeyPlayerList = new ArrayList<>();
        hockeyPlayerList.add(new HockeyPlayer("A", 3));
        hockeyPlayerList.add(new HockeyPlayer("D", 10));
        hockeyPlayerList.add(new HockeyPlayer("B", 2));

        System.out.println("Before Sort based on goalsScored\n");

        hockeyPlayerList.forEach(System.out::println);

        System.out.println("\nAfter Sort based on goalsScored\n");

        Collections.sort(
                hockeyPlayerList,
                (player1, player2) -> player1.getGoalsScored()
                        - player2.getGoalsScored());

        hockeyPlayerList.forEach(System.out::println);
    }

    static class HockeyPlayer {

        private String name;
        private int goalsScored;

        public HockeyPlayer(final String name, final int goalsScored) {
            this.name = name;
            this.goalsScored = goalsScored;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getGoalsScored() {
            return goalsScored;
        }

        public void setGoalsScored(int goalsScored) {
            this.goalsScored = goalsScored;
        }

        @Override
        public String toString() {
            return "HockeyPlayer [name=" + name + ", goalsScored="
                    + goalsScored + "]";
        }

    }
}

Output:

输出

Before Sort based on goalsScored

HockeyPlayer [name=A, goalsScored=3]
HockeyPlayer [name=D, goalsScored=10]
HockeyPlayer [name=B, goalsScored=2]

After Sort based on goalsScored

HockeyPlayer [name=B, goalsScored=2]
HockeyPlayer [name=A, goalsScored=3]
HockeyPlayer [name=D, goalsScored=10]

回答by Satyajit

With Java 8 this is simple

使用 Java 8 这很简单

Collections.sort(playList, Comparator.comparingInt(HockeyPLayer::goalsScored))