-3

I am getting all the keys in a map into a HashSet.

I want to be able to transfer this into an ArrayList.

5 Answers5

5

Did you mean this :

Map<K, V> map = new HashMap<>();
List<K> list = new ArrayList<>(map.keySet());
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

It appears you are already aware that Set<KeyType> set = map.keySet() returns a Set of the keys:

to put these into an ArrayList<KeyType> you can simply do new ArrayList(set);

MartinByers
  • 1,240
  • 1
  • 9
  • 15
0

Why not use the addAll method?

Set<KeyType> keys = map.keySet();
List<KeyType> res = new ArrayList<>();
res.addAll(keys);

No?

Nemesis
  • 2,750
  • 2
  • 22
  • 20
  • "No?" No! Never suggest to use raw types. – Tom Aug 29 '17 at 11:35
  • well this is just an exemple without types declared as the OP didn't provide is code... but nevermind i'm used to see comment of this sort assuming bad things one a simple excerpt of code... – Nemesis Aug 29 '17 at 11:40
  • Yeah, that's the issue with Stack Overflow trying to provide good quality answers. Stuff like your answer will then be downvoted, because they are far from "good quality". – Tom Aug 29 '17 at 11:41
0
Map<String,String> mymap = new HashMap<>();
// add data to the map
String[] array = mymap.keySet().toArray(new String[0]);
gufidown
  • 82
  • 1
  • 8
  • 2
    you populate an array not an ArrayList with this code. – Nemesis Aug 29 '17 at 11:41
  • 1
    Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Aug 29 '17 at 15:47
-1
Arrays.asList(map.keySet().toArray());

Would be a good place to start

PanBrambor
  • 89
  • 9