简体   繁体   English

如何以字母数字顺序对番石榴多图(键和值)进行排序(不区分大小写)

[英]How to sort the guava multimap(both key and value) in alphanumeric order(case insensitive)

I have a Person class: 我有一个Person类:

class Person {

    private String name;

    private String job;
    ... ...
}

I have a person list : 我有一个人名单:

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"))

I want to display the person list grouping by the job and both name and job are in alphanumeric order(case insensitive) as the following data formatting. 我想显示按工作分组的人员列表,姓名和工作都按字母数字顺序(不区分大小写)作为以下数据格式。

doctor
>>Aaron
>>Pete
>>pete
>>Vivian
teacher
>>Mary

Currently, I'm doing this: 目前,我正在这样做:

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());

I think the PersonComparator is not easy to read and understand. 我认为PersonComparator不容易阅读和理解。 Any better idea by directly using Guava API? 直接使用Guava API还有更好的主意吗? Thanks. 谢谢。

You might like to use a ComparisonChain 您可能想使用ComparisonChain

From what I gather, you want to first compare case-insensitively, and then if that is equal, perform the comparison in a case-sensitive way. 根据我的收集,您想首先不区分大小写地进行比较,然后如果相等,则以区分大小写的方式执行比较。

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();
}

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

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