Well, the Set.add() method returns a boolean value indicating if a new item was successfully added to the set. If it returns false is because the item was already there. Based on that you could easily write your algorithm. The ugly part is having to iterate the set to update the value, right?
if(!edges.add(newEdge)){
Iterator<Edge> iter = edges.iterator();
while(iter.hasNext()){
Edge edge = iter.next();
if(edge.equals(newEdge)){
edge.updateWeight(newEdge.getWeight()); //this.weight+=moreWeight
}
}
}
Based on this, I assume that what you want is just a way to beautify all this iteration boilerplate code.
A solution that I like is using LambdaJ Collections to update the weight of an existing Edge.
if (!edges.add(newEdge)) {
with(edges).first(is(newEdge)).updateWeight(newEdge.getWeight());
}
I do not know what you are looking for, but this approach would be just three lines of code. Quite simple from my point of view.
I wrote a small example to illustrate better the idea:
Jedi obiwan = new Jedi("Obiwan", 30, 40); // name, age and power
Jedi luke = new Jedi("Luke", 18, 25);
Jedi mace = new Jedi("Mace-Windu", 100, 450);
Jedi yoda = new Jedi("Yoda", 150, 1000);
Jedi obiAgain = new Jedi("Obiwan", 11, 40);
Set<Jedi> jedis = new HashSet<Jedi>(asList(obiwan, luke, mace, yoda));
if (!jedis.add(obiAgain)) {
with(jedis).first(is(obiAgain)).updatePower(obiAgain.getPower());
}
System.out.println(jedis);