簡體   English   中英

Java Multimap搜索價值

[英]Java Multimap search for value

我有一個Multimap,需要搜索值。 看起來像這樣

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

我需要將該名稱作為關鍵字,並且應該可以添加例如名稱為“ Bob”的兩個Persons。 該ID應該是唯一的。

例如:

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

我知道如何從地圖中獲取鍵“ Bob”的值。 但是,如何僅獲取ID為1的Bob的值?

如評論中所述, ListMultiMapget(String key)方法將返回給定鍵的元素List 由於您的person.id不是密鑰的一部分,因此不會對返回的列表產生任何影響。

就像IK在接受的答案中所說的那樣,您可以簡單地遍歷返回的列表以獲取具有給定ID的人。

但是,更合適的數據結構可能是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();

這將檢索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
    }
}

雖然檢查的答案是正確的,但我認為全番石榴解決方案更加優雅:

   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