简体   繁体   中英

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

I have a Person class:

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. Any better idea by directly using Guava API? Thanks.

You might like to use a 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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