Frank
Frank

Reputation: 1027

what's the difference between Map.Entry and map.get(key)

I have a concern about which method is better, Map.Entry or map.get(key), the structure of rows is List< Map< String, Object>> the code below as:

for (Map<String, Object> row : rows) {
    Object stock = row.get("stock");
}

the other:

for (Map<String, Object> row : rows) {
    for (Map.Entry<String, Object> cell : row.entrySet()) {
        if (cell.getKey().equals("stock")) {
            Object stock = cell.getValue();
        }
    }
}

Which one is better?

and there is another question I curious about, I have only known some key names but not all, I want to get all the values from the map, how should I do? btw, I don't wanna use entrySet iterator method.

for (Map<String, Object> row : rows) {
   Object stock = row.get("stock");
  Object itemId = row.get("itemid");
  Object modelId = row.get("modelid");

   // todo
  // how to get other values that I don't know the key name String}

Upvotes: 1

Views: 904

Answers (2)

GhostCat
GhostCat

Reputation: 140465

which one is better?

Typically, in programming, there is no universal better. Things always depend on context.

Having said that, when writing code, you strive to "do what needs to be done" with the least amount of code (that is easy to read and understand).

From that point of view, your first option is the clear winner. It gets the job done, is easier to read and maintain (mainly because you look at less code). Where the job is: iterate over all entries in the map, and do something with each value.

From a "semantical" point of view, the two options "do the same thing", so they are mostly equivalent, I really can't think of an example where you end up with different behavior for the two options (except the different cost at runtime, see that other answer).

Upvotes: 3

Eran
Eran

Reputation: 393856

The first snippet is better, since you seem to need just the value of a single key.

using row.get("stock") will take constant (O(1)) expected time.

Iterating over the entrySet and comparing the key of each Map.Entry to the required key, on the other hand, will take linear (O(n)) time, which is much worse than the first snippet when the Map is large.

You should only iterate over the entire entrySet if you need to process all the entries of the Map.

Upvotes: 3

Related Questions