How to convert hash map keys into list?
95,475
Solution 1
Your uniqueRecs
has String
type of the key. You have to do:
List<String> keys = new ArrayList<>(uniqueRecs.keySet());
or
List<ARecord> values = new ArrayList<>(uniqueRecs.values());
Solution 2
What worked for me that i wanted to modify an existing list was:
list.addAll(map.keySet());
Solution 3
I think the best way to do this 'nowadays' is:
List<Integer> result = map.keySet().stream().collect(Collectors.toList());
This will not throw any warnings and will get the List<Integer>
generic correctly.
Related videos on Youtube
Author by
Jay
Updated on December 14, 2020Comments
-
Jay over 3 years
I have a hash map and I'm trying to convert the keys to a list. Here's the code:
List<ARecord> recs = new ArrayList<ARecord>(); HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>(); for(ARecord records:recs){ if(!uniqueRecs.containsKey(records.getId())){ uniqueRecs.put(records.getId(), records); } }
When I try to do
List<ARecord> finalRecs = new ArrayList<ARecord>(uniqueRecs.keySet());
The error:
The constructor ArrayList(Set) is undefined".
How can I convert Hashmap keys to
List<ARecord>
finalRecs? -
Jay almost 9 yearsI get an error"The method addAll(Collection<? extends ARecord>) in the type List<ARecord> is not applicable for the arguments (Set<String>)"
-
schtever almost 9 years@Jay revised the answer to populate the list with the Map's values not the keys.
-
Jay almost 9 yearswould there be any way to convert List<String> keys into List<ARecord>?
-
Jay almost 9 yearsI actually want the keys. Is there any way to get keys and convert to List<ARecord>?
-
ka4eli almost 9 yearsARecords in you map are not the keys, they are values! You have to decide list of what entities you want to get in the end: ARecords or Strings. If ARecords - then take values of a Map, if Strings - take keySet.
-
Jay almost 9 yearsI want keySet. Once I get that, I pass into another method which takes in List<ARecord>. I can't figure out how to pass the keys of hash map as a List<ARecord>
-
Louis Wasserman almost 9 years@Jay: That statement makes no sense. The keys are
String
s. "how to pass the keys of hash map as a List<ARecord>" makes no sense, because the keys are notARecord
s. That's the values. -
Jay almost 9 yearsit's an interface: public interface ARecord {public String gettId()}
-
Mick Mnemonic almost 9 years@Jay, if the records in
uniqueRecs
are indeed unique as the name implies, meaning that allARecord
s in the map have unique ids, then you can simply usenew ArrayList<>(uniqueRecs.values())
as ka4eli is suggesting here. -
Mark over 7 yearsThank you - to elaborate/explain further
keySet()
returns aSet
and thisextends
theCollection
class.values()
returns aCollection
. This :public ArrayList(Collection<? extends E> c)
fromArrayList
constructor makes it valid.