我有一个Person类:
class Person {
private String name;
private String job;
... ...
}
我有个人名单:
personList.put(new Person("Pete","doctor"))
personList.put(new Person("pete","doctor"))
personList.put(new Person("Aaron","doctor"))
personList.put(new Person("Vivian","doctor"))
personList.put(new Person("Mary","teacher"))
我想显示作业的人员列表分组,名称和作业都是字母数字顺序(不区分大小写),作为以下数据格式。
doctor
>>Aaron
>>Pete
>>pete
>>Vivian
teacher
>>Mary
目前,我正在这样做:
public enum PersonComparator implements Comparator<Person> {
NAME_JOB_INSENSTIVE_ASC {
@Override
public int compare(final Person obj1, final Person obj2) {
String compareObj1 = obj1.getName();
String compareObj2 = obj2.getName();
int compareValue = compareObj1.compareTo(compareObj2);
int compareValueIgnoreCase = compareObj1.compareToIgnoreCase(compareObj2);
if(compareValueIgnoreCase == 0) {
return compareValue >= 0 ? 1 : -1;
} else {
return compareValueIgnoreCase>= 0 ? ++compareValueIgnoreCase
: --compareValueIgnoreCase;
}
}
}
}
ListMultimap<String, Person> personTableList = Multimaps.index(personList,
new Function<Person, String>() {
@Override
public String apply(Person person) {
return person.getJob();
}
});
TreeMultimap<String, Person> personTableTree = TreeMultimap.create(Ordering.natural(),
PersonComparator.NAME_JOB_INSENSTIVE_ASC);
personTableTree.putAll(personTableList);
model.addAttribute(RequestParameter.Person_TABLE, personTableTree.asMap());
我认为PersonComparator不易阅读和理解。通过直接使用Guava API有什么好主意吗?感谢。
答案 0 :(得分:2)
您可能想要使用ComparisonChain
从我收集的内容来看,您首先要比较不区分大小写,然后如果相等,则以区分大小写的方式执行比较。
public int compare(final Person p1, final Person p2)
{
return ComparisonChain.start()
.compare(p1.getName().toLowerCase(), p2.getName().toLowerCase())
.compare(p1.getName(), p2.getName())
.result();
}