Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g. 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?

like image 661
user2348157 Avatar asked May 31 '26 11:05

user2348157


2 Answers

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 I.K. 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 Maps, 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();
like image 102
Pierre Henry Avatar answered Jun 03 '26 01:06

Pierre Henry


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
    }
}

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!