简体   繁体   中英

Java Multimap search for value

I have a Multimap and need to search for the values. It looks like this

ListMultiMap<String, Person> pers =  ArrayListMultimap.create();
....
Person person = new Person();
person.setName(name);
peson.setAge(age);
person.setId(id);
...
pers.put(name, person);

I need the name as a key, and it should be possible to add eg two Persons with Name "Bob". The ID should be unique.

For Example:

Name: Bob, ID:1
Name: Bob, ID:2

I know how to get the values for the key "Bob" out of the map. But how can I get only the values for Bob with the ID 1?

As mentioned in the comments, the get(String key) method of ListMultiMap will return a List of elements for the given key. Since your person.id is not part of the key, it will not have any impact on the returned list.

As IK said in the accepted answer, you can simply iterate over the returned list to get the person with the given ID.

However a better suited data structure might be the Guava Table , that allows you to have 2 keys (you can also think of if as a sort of Map of Map s, or in your case Map<String,Map<Long, Person>> ) :

Table<String, Long, Person> personsByNameAndId = HashBasedTable.create();
Person bob = ...;
//put it in the table
personsByNameAndId.put(bob.getName(), bob.getId(), bob);

//lookup by name and ID
Person bobWithId1 = personsByNameAndId.get("Bob", 1l);

//get all Bobs
Collection<Person> allPersonsNamedBob = personsByNameAndId.row("bob").values();

//get person with ID=2 regardless of name
Person personWithId2 = personsByNameAndId.column(2l).values().iterator().next();

This will retrieve the person Bob with an ID of 1:

ListMultiMap<String, Person> pers =  ArrayListMultimap.create();
List<Person> persons = pers.get("Bob");
for(Person p : persons){
    if (p.getId() == 1){
        //do something
    }
}

While the checked answer is correct, I think the all-guava solution is more elegant:

   Multimap<String, Person> pers =  ArrayListMultimap.create();
   Person firstBob = FluentIterable.from(pers.get("Bob")).firstMatch(new Predicate<Person>() {
        @Override
        public boolean apply(Person p) {
            return p.getId() == 1;
        }
    });

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