[英]I have a problem which is sorting by two fields with comparator in java
因此,我试图按状态然后按城市对arrayList进行排序(如果存在重复的状态,则对城市进行比较)。 但是我无法使它起作用,因为它只能对州或城市进行排序。 任何帮助,将不胜感激。
class StateCityComparator implements Comparator<Customer>{
/**
* Comapre method that compares Customers by state and city
* @param first, second which are the numbers of the customer which needs to be compared
*/
public int compare(Customer first, Customer second){
// Getting the state
String fir = first.getState();
String sec = second.getState();
int state = fir.compareTo(sec);
int city = first.getCity().compareTo(second.getCity());
// Comparing the state
if (state < 0)
return -1;
if ( state == 0 ){ /* The problem is here */
return city;
}
return state;
}// End of compareStateCity
} // end StateCityComparator
这是输出的一部分:
Sorted by State and City:
3 Mapleview Drive Huntsville AL 358030000
2421 West Industrial Way Berkeley CA 947100000
2421 West Industrial Way Berkeley CA 947100000
4223 Halster Way Berkeley CA 947101234
4223 Halster Way Berkeley CA 947104321
4 Rocky Way Colorado Springs CO 809410000
4 Rocky Way Colorado Springs CO 809410000
5665 MassPike Circle Sandy Hook CT 064820000
45A Sturgeon Dr., Bldg. 5 Ft. Pierce FL 349510000
45A Sturgeon Dr., Bldg. 5 Ft. Pierce FL 349510000
6665 Peachtree Lane Atlanta GA 303280000
1 Washington Complex Boston MA 021010000
45521 Pilgrim Circle Nantucket MA 025540000
您可以使用Comparator.comparing(...)
和Comparator.thenComparing(...)
轻松地为数据对象编写Comparator
,如下所示:
public static final Comparator<Customer> STATE_CITY_COMPARATOR =
Comparator.comparing(Customer::getState).thenComparing(Customer::getCity);
我认为这就是您想要的(保持代码的顶部相同):
class StateCityComparator implements Comparator<Customer> {
/**
* Compare method that compares Customers by state and city
* @param first, second which are the numbers of the customer which needs to be compared
*/
@Override
public int compare(Customer first, Customer second){
// Getting the state
String fir = first.getState();
String sec = second.getState();
int state = fir.compareTo(sec);
int city = first.getCity().compareTo(second.getCity());
// Compare the state, and the city if the states are equal
return (state == 0)? city : state;
}// End of compareStateCity
} //
或更简而言之,如果不需要,请避免比较城市:
class StateCityComparator implements Comparator<Customer> {
/**
* Compare method that compares Customers by state and city
* @param first, second which are the numbers of the customer which needs to be compared
*/
@Override
public int compare(Customer first, Customer second){
int state = first.getState().compareTo(second.getState());
return (state != 0)? state : first.getCity().compareTo(second.getCity());
}// End of compareStateCity
} //
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.