0

I am using HashMap with integer keys,

HashMap<Integer, Double> feature_vector = new HashMap<Integer, Double>();

and while reading data, add a new member when the value is not 0,

if (value != 0)
                feature_vector.add(index, value);

For anything that deals with this feature_vector, how can I just iterate over the "non-empty" positions of this feature_vector? I don't want to increment the key from 0 to the size of the feature_vector and check the value of every single key, which slows the program down.

Meaning there will be cases when the feature vector looks like: 1->7, 3->0, 4->5, 5->9, ... (the second key has no value, so there would not be a second key and its value)

Thanks in advance for your time and help!

3
  • 1
    If you're already not adding indexes that have zero values to the map, then the only entries inside will be the nonzero ones. You can use the HashMap.entrySet() method (which is iterable) to explore the contents (both keys and values together), or use HashMap.keySet() for just the keys (indices). Commented Sep 12, 2014 at 4:10
  • Damn, totally forgot about the entrySet() method... Thank you William! Commented Sep 12, 2014 at 4:13
  • Not sure if it's required but if you use a TreeMap instead of a 'HashMap', the keys / entries will be sorted by Integer value. Commented Sep 12, 2014 at 11:03

2 Answers 2

2

More efficient than iterating over keys is to iterate directly over key-value pairs:

for (Map.Entry<Integer,Double> entry : feature_vector.entrySet()) {
  Integer key = entry.getKey();
  Double value = entry.getValue();
  ...
}

This avoids looking up the value.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this:

    Set<Integer> keys = feature_vector.keySet();

    for(Integer key : keys) {
        Double value = feature_vector.get(key);
        //do what ever you want with the key and value in here...
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.