Results 1 to 2 of 2
  1. #1
    desmond5 is offline Member
    Join Date
    Mar 2008
    Posts
    2
    Rep Power
    0

    Default Retreiving list of keys from Map with certan value

    Hello,

    I have a map (doesn't matter if it's hashmap or treemap or whaterer, just as long as it has keys and values).
    I have several keys (of Person) in the map that have the same value (of Job).

    public class Person
    {
    private String name;

    public Person (String name) {
    this.name = name;
    }

    @Override
    public String toString() {
    return this.name;
    }
    }

    public class Job {

    private String name;

    public Job (String name) {
    this.name = name;
    }

    @Override
    public String toString() {
    return this.name;
    }
    }
    How can I retreive a list of keys which have the same value in the map ? Or In another words, how can I retreive a list of persons who all have the same Job ?
    Is a map a good choice here at all ?

    Many many thanks and best wishes,
    desmond5

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Make up a method that will take the Job you are looking for and collect all Person keys in the map that have the same value as the Job argument.
    Java Code:
    Map<Person, Job> map = new HashMap<Person, Job>();
    
    private List<Person> getPeopleByJob(Job job) {
        List<Person> list = new ArrayList<Person>();
        Set<Person> keys = map.keySet();
        Iterator<Person> it = keys.iterator();
        while(it.hasNext())
            Person person = (Person)it.next();
            if(map.get(person).equals(job))
                list.add(person);
        }
        return list;
    }

Similar Threads

  1. Retreiving of mail body using mail number
    By chandu.v09 in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 03-13-2008, 02:25 PM
  2. Replies: 1
    Last Post: 02-01-2008, 01:21 PM
  3. Uisng primitive type values as keys for Hashtable
    By ravian in forum New To Java
    Replies: 3
    Last Post: 11-21-2007, 10:13 AM
  4. list
    By Zensai in forum New To Java
    Replies: 3
    Last Post: 11-20-2007, 07:22 AM
  5. How to get the max value from a list
    By osval in forum New To Java
    Replies: 1
    Last Post: 07-30-2007, 05:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •