Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Maps.uniqueIndex doesn't allow duplicates

Tags:

guava

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();
}});
like image 813
Marc Avatar asked Oct 31 '25 08:10

Marc


1 Answers

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

like image 166
Philipp Wendler Avatar answered Nov 03 '25 10:11

Philipp Wendler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!