2

I have a hashmap that contains, person Id as key, and person object as value.

Map<String, Person> personMap = new HashMap<String,Person>();

The person object (map's value) contains a person Id instance variable that I'd like to compare with user input. My idea is to create an arraylist from the map's values as mentioned here - How to convert a Map to List in Java?, so I can check if the arraylist.contains(userInput).

However, I need a arraylist of strings that contains Person.getPersonId(),please help me here. Can I do it in one step? If there is a better alternative then, please suggest.

Community
  • 1
  • 1
rickygrimes
  • 2,637
  • 9
  • 46
  • 69
  • 1
    Why would you want to convert the values to an `ArrayList`? Are you just trying to find a particular key in the map? Can't you just use `get` for this? – Dawood ibn Kareem Nov 03 '13 at 06:38
  • Yes - can you verify whether the `String` key from the `Map` is, in-fact, the same as ther `personId` field on the `Persion` objects? If so, then all this list stuff is completely backwards and unnecessary - you are completely ignoring the intended function of the `Map` – torquestomp Nov 03 '13 at 06:43

2 Answers2

5

At first, you need to get Person values from personMap.

List<Person> persons =personMap.values();

To get arraylist of strings that contains Person.getPersonId(), you need to do following steps.

List<String> personIds=new ArrayList<>();
for(Person p: persons){ // Iterate over persons List
  if(p.getPersonId()!=null){ //Check the personId from Person
    personIds.add(p.getPersonId());
  }
}
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

Try this:

List<Person> personList = new ArrayList<>(personMap.values());
List<String> idList = personList.stream().map(Person::getPersonId).collect(Collectors.toList());
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
Iridium Cao
  • 51
  • 1
  • 8