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 a name and an attribute1 (but no attribute2).
servers2 contains servers with a name and an attribute2 (but no attribute1).
public class Server {
private String name;
private String attribute1;
private String attribute2;
public Server(String name) {
this.name = name;
this.attribute1 = "";
this.attribute2 = "";
}
//Getters & Setters
}
Does anyone know how I can merge these two lists to one list containing
each Server only once (by name) but with both attributes?
There are servers which only exist in 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 result in:
[Server [name=MyServer, attribute1=Attribute1, attribute2=Attribute2],
Server [name=MyServer2, attribute1=Attribute1.2, attribute2=]]
Server [name=MyServer3, attribute1=, attribute2=Attribute2.2]]
//SOLUTION (thx everybody 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;
}));
nametoServerfromservers1and then fill the missingattribute2fromservers2looking up the server in the map by name. Try to write some code on your own.Serverclass, how do the entities in eitherListhave any values forname,attribute1orattribute2. If this is not the entire class, please include constructor(s)