如何从hashmap中只获取一个包含键字符串的值,并列出<object>

时间:2018-04-12 13:42:34

标签: java arraylist hashmap

如何从hashmap中只获取一个包含键字符串和列表

的值

散列映射:

HashMap<String, ArrayList<Person>> person = new HashMap<String, ArrayList<Person>>();

构造函数Person:

Person(int phone, String mail){
    this.phone = phone;
    this.mail = mail;
}

获取对象的方法:

protected void findObject(String lname){
    if (person.containsKey(lname)) {
            System.out.println(lname + " phone: " + person.get(lname));
    }
}

但我需要两种方法:

protected void findPhone(String lname){
//should get only phone from Person;
}

protected void findMail(String mail){
//should get only mail from Person;
}

像这样工作:

protected List<Integer> findPhone(String lname) {
    List<Integer> listPhone = null;
    if (person.containsKey(lname)) {
        listPhone = person.get(lname).stream()
        .map(Person::getPhone)
        .collect(Collectors.toList());

    }
    return listPhone;
}

protected List<String> findMail(String lname) {
    List<String> listMail = null;
    if (person.containsKey(lname)) {
        listMail = person.get(lname).stream()
        .map(Person::getPhone)
        .collect(Collectors.toList());

    }
    return listmail;
}

1 个答案:

答案 0 :(得分:1)

如果您使用的是Java 8,则可以使用:

list_sentences

protected void findPhone(String lname) {
    if (person.containsKey(lname)) {
        List<Integer> listPhone = person.get(lname).stream()
                .map(Person::getPhone)
                .collect(toList());
    }
}