title: How to model HashMap/Dictionary in the ProtoBuf efficiently
body: <p>I have a protobuf file serialized by .NET code and I would like to consume it into Java. In the .NET code, there is Dictionary data type and the proto schema looks like </p>
  
  <pre><code>message Pair {
     optional string key = 1;
     optional string value = 2;
  }
  
  message Dictionary {
     repeated Pair pairs = 1;
  }
  </code></pre>
  
  <p>Just as described in stackoverflow post 
  <a href="https://stackoverflow.com/questions/4194845/dictionary-in-protocol-buffers">Dictionary in protocol buffers</a>.</p>
  
  <p>I can use protoc to compile the proto file into Java classes fine. I can deserialize the protobuf file into Java objects successfully. The only problem is that it translates to a <strong>List</strong> of Pair objects in Java instead of <strong>HashMap</strong>. Of course, I still have all the data, but <strong>I cannot access the data as efficiently as I prefer</strong>. If I have the value of the key, I have to loop through the whole list to get its corresponding value. This does not seem to be optimal.</p>
  
  <p>I am wondering if there is a better way to model Dictionary/Map data type in the protobuf.</p>
  
  <p>Thanks</p>
  
  <p><strong>Update:</strong></p>
  
  <p>I tried Jon Skeet's suggestion to add map type field in the addressbook example and still ran into issue. </p>
  
  <pre><code>message Person {
    required string name = 1;
    required int32 id = 2;        // Unique ID number for this person.
    optional string email = 3;
    enum PhoneType {
      MOBILE = 0;
      HOME = 1;
      WORK = 2;
    }
    message PhoneNumber {
      required string number = 1;
      optional PhoneType type = 2 [default = HOME];
    }
    repeated PhoneNumber phone = 4;
    map&lt;string, string&gt; mapdata = 5;
  }
  </code></pre>
  
  <p>The protoc throws error when compiling</p>
  
  <pre><code>addressbook.proto:25:3: Expected "required", "optional", or "repeated".
  addressbook.proto:25:6: Expected field name.
  </code></pre>
  
  <p>According to Google protobuf doc, proto 2 does support map type <a href="https://developers.google.com/protocol-buffers/docs/proto#maps" rel="noreferrer">https://developers.google.com/protocol-buffers/docs/proto#maps</a> . As I quote, </p>
  
  <blockquote>
    <p>Maps cannot be repeated, optional, or required.</p>
  </blockquote>
  
  <p>So I don't really know why protoc cannot compile it. There is another discussion here <a href="https://stackoverflow.com/questions/29407123/have-to-create-java-pojo-for-the-existing-proto-includes-map">have to create java pojo for the existing proto includes Map</a>. The answer suggests that map is only a proto 3 feature. This contradicts google's documentation.</p>