Hashmap | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Hashmap

public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); HashMap<String, Integer> ages = new HashMap<>(); ages.put("Tom", 22); ages.put("Nick", 30); ages.put("Eric", 44); String[] nameArr = new String[ages.size()]; nameArr = ages.keySet().toArray(nameArr); int ageLimit = sc.nextInt(); for (String emp : nameArr) { if ( ages.get(emp) < ageLimit) { ages.remove(emp); } } System.out.println(ages); } } Guys, for what I need the String " nameArr = ages.keySet().toArray(nameArr); " ? It get only the key word from hashmap and add it to array "nameArr"?

6th Apr 2021, 10:10 PM
Par9shiy
Par9shiy - avatar
2 Answers
+ 2
Yes. It is getting the keys of the hashmap `ages` and putting them into the array `nameArr` `ages.keySet()` returns a `Set` of keys of the hasmap, that is ("Tom", "Nick", "Eric"). Then calling the toArray() method on the `Set` puts the elements of the set into the array passed as argument. Just a side note, instead of `nameArr = ages.keySet().toArray(nameArr);` You can just do `ages.keySet().toArray(nameArray)` As the .toArray() method makes changes directly to the array. So you don't need to assign it. It works currently because the .toArray() method returns the array passed as argument after making the changes.
7th Apr 2021, 4:03 AM
XXX
XXX - avatar
0
also this is shorter ages.values().removeIf( age -> age < ageLimit);
7th Apr 2021, 9:15 AM
zemiak