如何在Java中按两个字段排序?我有一系列的对象person (int age; String name;).我如何按名称和年龄按字母顺序对这个数组进行排序?你会用哪种算法来解决这个问题?
3 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
//Creates and sorts a stream (does not sort the original list) persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
//Sorts the original list Lambda stylepersons.sort((p1, p2) -> { if (p1.getName().compareTo(p2.getName()) == 0) { return p1.getAge().compareTo(p2.getAge()); } else { return p1.getName().compareTo(p2.getName()); } });
//This is similar SYNTAX to the Streams above, but it sorts the original list!! persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
添加回答
举报
0/150
提交
取消