我正在尝试排序并打印按 ID 排序的 ArrayList
。
clientArr.sort( (p1, p2) -> p1.getAccount().getID().compareTo(p2.getAccount().getID()) );
for(Client client : clientArr)
System.out.println(client);
我相信我的问题是因为 p1
和 p2
期望返回对象,但它们正在获取 int
值。我该如何解决这个问题?
ArrayList存储Client对象。 Client 类包含字符串值(在本例中并不重要),并且它创建一个 Account 对象的实例。 Account 类中存储了 int ID 值。这就是我需要的值
最佳答案
使用Integer.compare(int, int)
就像,
clientArr.sort((p1, p2) -> Integer.compare(p1.getAccount().getID(),
p2.getAccount().getID()));
此外,您的 for-each
循环可以重写为
clientArr.forEach(System.out::println);
关于java - 使用 Lambda 解引用 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485165/