简体   繁体   English

Java Multimap搜索价值

[英]Java Multimap search for value

I have a Multimap and need to search for the values. 我有一个Multimap,需要搜索值。 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". 我需要将该名称作为关键字,并且应该可以添加例如名称为“ Bob”的两个Persons。 The ID should be unique. 该ID应该是唯一的。

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. 我知道如何从地图中获取键“ Bob”的值。 But how can I get only the values for Bob with the ID 1? 但是,如何仅获取ID为1的Bob的值?

As mentioned in the comments, the get(String key) method of ListMultiMap will return a List of elements for the given key. 如评论中所述, ListMultiMapget(String key)方法将返回给定键的元素List Since your person.id is not part of the key, it will not have any impact on the returned list. 由于您的person.id不是密钥的一部分,因此不会对返回的列表产生任何影响。

As IK said in the accepted answer, you can simply iterate over the returned list to get the person with the given ID. 就像IK在接受的答案中所说的那样,您可以简单地遍历返回的列表以获取具有给定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>> ) : 但是,更合适的数据结构可能是Guava Table ,它可以让您拥有2个键(您也可以将它视为Map一种Map ,或者在您的情况下考虑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: 这将检索ID为1的个人Bob:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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