Search code examples
guava

Guava Maps.uniqueIndex doesn't allow duplicates


When I use Maps.uniqueIndex with a List that contains a duplicate value,

java.lang.IllegalArgumentException: duplicate key: 836
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:115)

is thrown.

I find this inconvenient. I suppose it does make some sense, but if a unique collection is required for the function to work correctly, why does it accept an Iterable as an argument in stead of a Set?

List<GroupVO> groups = groupDao.getAll(groupIds);

Map<String,GroupVO> groupMap groupMap = Maps.uniqueIndex(groups, new Function<GroupVO,String>() {
    public String apply(GroupVO vo) {
        return vo.getId().toString();
}});

Solution

  • It is simply not possible to have multiple values for one key in a plain Map, thus uniqueIndex cannot do anything else.

    It accepts Iterable because accepting only Set would restrict its possible usages and still not solve the problem. Not the values in the given Iterable need to be unique, but the result of applying the given function on each of them.

    If you need multiple values per key, you can simply use Multimaps.index, which does the same but returns a Multimap (which can contain an arbitrary number of values per key).