Как заполнить текстовый массив ключами HashMap? Java
У меня есть карта с названем "CartoonCollection", ключи все которого — являются названиями популярных мультфильмов:
HashMap<String, Integer> CartoonCollection = new HashMap<String, Integer>();
hashMap.put("History of toys", 5); //Значения — рандомные числа, они не важны
hashMap.put("Lion king", 8);
hashMap.put("Spirited Away", 12);
hashMap.put("The beauty and the Beast", 5);
hashMap.put("Bambi", 9);
hashMap.put("Snow White and the 7 Dwarfs", 2)
Я хочу создать массив, где будут хранится все ключи CartoonCollection:
String[] massive = new String[6];
И вот, что мне удалось написать:
for (int i = 0; i<6; i++) {
for (String key : Cartoon.CartoonCollection.keySet()) {
massive[i] = key;
}
}
Когда я вывожу "massive" на консоль, то результат таков:
for (int j = 0; j<massive.length; j++) {
System.out.println(massive[j]);
}
|Output|
Snow White and the 7 Dwarfs
Snow White and the 7 Dwarfs
Snow White and the 7 Dwarfs
Snow White and the 7 Dwarfs
Snow White and the 7 Dwarfs
Snow White and the 7 Dwarfs
Что я делаю не так?
Ответы (2 шт):
Автор решения: Igor
→ Ссылка
int i = 0;
//for (int i = 0; i<6; i++) {
for (String key : Cartoon.CartoonCollection.keySet()) {
massive[i++] = key;
}
//}
Автор решения: Sergey
→ Ссылка
Есть более интересные способы создать массив, не путаясь в циклах
String[] massive = Cartoon.CartoonCollection.keySet().toArray(new String[0]);
или так, чтобы не создавать лишний массив-образец
Set<String> cartoonKeys = Cartoon.CartoonCollection.keySet();
String[] massive = cartoonKeys.toArray(new String[cartoonKeys.size()]);
или так
String[] massive = Cartoon.CartoonCollection.keySet().stream()
.toArray(String[]::new);