title: Java 8: Merging two Lists containing objects by key
body: <p>I have two lists:</p>
  
  <pre><code>List&lt;Server&gt; servers1 = new ArrayList&lt;&gt;();
  Server s1 = new Server("MyServer");
  s1.setAttribute1("Attribute1");
  servers1.add(s1);
  
  List&lt;Server&gt; servers2 = new ArrayList&lt;&gt;();
  Server s2 = new Server("MyServer");
  s2.setAttribute2("Attribute2");
  servers2.add(s2);
  </code></pre>
  
  <p><code>servers1</code> contains servers with a <code>name</code> and an <code>attribute1</code> (but no <code>attribute2</code>).<br/>
  <code>servers2</code> contains servers with a <code>name</code> and an <code>attribute2</code> (but no <code>attribute1</code>).</p>
  
  <pre><code>public class Server {
     private String name;
     private String attribute1;
     private String attribute2;
  
     public Server(String name) { 
         this.name = name;
         this.attribute1 = "";
         this.attribute2 = "";
     }
  
     //Getters &amp; Setters
  
  }
  </code></pre>
  
  <p>Does anyone know how I can merge these two lists to one list containing
  each <code>Server</code> only once (by <code>name</code>) but with both attributes?</p>
  
  <p>There are servers which only exist in one or the other list.
  The final list should contain all servers.</p>
  
  <pre><code>    List&lt;Server&gt; servers1 = new ArrayList&lt;&gt;();
      Server s1 = new Server("MyServer");
      s1.setAttribute1("Attribute1");
  
      Server s2 = new Server("MyServer2");
      s2.setAttribute1("Attribute1.2");
  
      servers1.add(s1);
      servers1.add(s2);
  
      List&lt;Server&gt; servers2 = new ArrayList&lt;&gt;();
      Server s3 = new Server("MyServer");
      s3.setAttribute2("Attribute2");
  
      Server s4 = new Server("MyServer3");
      s4.setAttribute2("Attribute2.2");
  
      servers2.add(s3);
      servers2.add(s4);
  </code></pre>
  
  <p>should result in:</p>
  
  <p>[Server [name=MyServer,  attribute1=Attribute1,   attribute2=Attribute2],</p>
  
  <p>Server [name=MyServer2, attribute1=Attribute1.2, attribute2=]]</p>
  
  <p>Server [name=MyServer3, attribute1=,             attribute2=Attribute2.2]]</p>
  
  <p><strong>//SOLUTION</strong> (thx everybody for the help!)</p>
  
  <pre><code>Map&lt;String, Server&gt; serverMap1 = Stream.concat(servers1.stream(), servers2.stream())
              .collect(Collectors.toMap(Server::getName, Function.identity(), 
              (server1, server2) -&gt; {
                  server1.setAttribute2(server2.getAttribute2()); 
                  return server1; 
              }));
  </code></pre>