221b
221b

Reputation: 431

Convert HashMap key value (String) to Vector <String>?

I have a hashmap declared as :

HashMap<String, Double> hm = new HashMap<String, Double>();

I'm declaring a Vector as :

 Vector<String> productList = new Vector<String>();

Now, I'm trying to add the keys into the vector :

  Set set = hm.entrySet();
  // Get an iterator
  Iterator i = set.iterator();
  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
     //System.out.print(me.getKey() + ": ");
     productList.add(me.getKey());
     //System.out.println(me.getValue());
  }

//hm is the HashMap holding the keys and values.

When I compile the code it gives the following error:

ProductHandler.java:52: error: no suitable method found for add(Object)
     productList.add(me.getKey());
                ^
method Collection.add(String) is not applicable
  (argument mismatch; Object cannot be converted to String)

Do we need to convert the values to String type before trying to add it to the vector? Am I missing out on something?

Upvotes: 3

Views: 8373

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201467

First, you can do it in one line with the Vector(Collection<? extends E) constructor and a call to Map.keySet() like

Vector<String> productList = new Vector<>(hm.keySet());

Second, you should prefer an ArrayList1

List<String> productList = new ArrayList<>(hm.keySet());

1Unless you're sharing this list with multiple threads, adding synchronization with a Vector is a cost.

Upvotes: 5

Eran
Eran

Reputation: 393936

Don't use raw types.

Your code can be much simpler with enhanced for loop :

  for(String key : hm.keySet()) {
     productList.add(key);
  }

or

  for(Map.Entry<String,Double> entry : hm.entrySet()) {
     productList.add(entry.getKey());
  }

Upvotes: 2

Related Questions