I have two lists:
List<Server> servers1 = new ArrayList<>(); Server s1 = new Server("MyServer"); s1.setAttribute1("Attribute1"); servers1.add(s1); List<Server> servers2 = new ArrayList<>(); Server s2 = new Server("MyServer"); s2.setAttribute2("Attribute2"); servers2.add(s2);
servers1 contains servers with name and attribute1 (but not attribute2 ).
servers2 contains servers with name and attribute2 (but not attribute1 ).
public class Server { private String name; private String attribute1; private String attribute2; public Server(String name) { this.name = name; this.attribute1 = ""; this.attribute2 = ""; }
Does anyone know how I can combine these two lists into one list containing each Server only once (via name ), but with both attributes?
There are servers that exist on only one or the other list. The final list should contain all servers.
List<Server> servers1 = new ArrayList<>(); Server s1 = new Server("MyServer"); s1.setAttribute1("Attribute1"); Server s2 = new Server("MyServer2"); s2.setAttribute1("Attribute1.2"); servers1.add(s1); servers1.add(s2); List<Server> servers2 = new ArrayList<>(); Server s3 = new Server("MyServer"); s3.setAttribute2("Attribute2"); Server s4 = new Server("MyServer3"); s4.setAttribute2("Attribute2.2"); servers2.add(s3); servers2.add(s4);
should get:
[Server [name = MyServer, attribute1 = Attribute1, attribute2 = Attribute2],
Server [name = MyServer2, attribute1 = Attribute1.2, attribute2 =]]
Server [name = MyServer3, attribute1 =, attribute2 = Attribute2.2]]
// SOLUTION (thanks for the help!)
Map<String, Server> serverMap1 = Stream.concat(servers1.stream(), servers2.stream()) .collect(Collectors.toMap(Server::getName, Function.identity(), (server1, server2) -> { server1.setAttribute2(server2.getAttribute2()); return server1; }));