简体   繁体   English

对象java列表上的Collections.sort

[英]Collections.sort on list of object java

I'm need to make sure i understand correctly someone else code at work this block sort this object: theObjectList by the variable getId() what do i need to do in order to add another variable to the sorting ? 我需要确保我正确理解了在工作的其他代码,此代码块对该对象进行了排序:由变量getId()组成的theObjectList我需要做什么才能向排序中添加另一个变量? for example getName() 例如getName()

    protected void fillData(List<AnyObject> theObjectList) {
        Collections.sort(theObjectList, (A, B) -> A.getId() - B.getId());
/*  more code */
}

You can use Comparators.comparing 您可以使用Comparators.comparing

Collections.sort(theObjectList, 
                 Comparator.comparing(x -> x.getId()).andThen(x -> x.getName()));

Believe you'd need to understand and pickup lambda expressions. 相信您需要了解并获取lambda表达式。 They have been introduced since jdk8 . jdk8开始引入它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM