class Player {
private String name;
private int id;
public Player(int id) {
this.id = id;
this.name = "Player " + id;
}
@Override
public int hashCode() {
return this.id;
}
@Override
public String toString() {
return this.name;
}
}
Player[] players = new Player[5];
IntStream.range(0, players.length).forEach(i -> players[i] = new Player(i + 1));
// -------------------------------------------------------------------------
HashMap<Player, String> original = new HashMap<>();
original.put(players[0], "Hello");
original.put(players[1], "Hi");
original.put(players[2], "Hi");
original.put(players[3], "Hello");
original.put(players[4], "Hello");
HashMap<String, HashMap<Player, String>> duplicates = new HashMap<>();
original.keySet().stream().forEach(key -> {
String value = original.get(key);
HashMap<Player, String> duplicate = duplicates.get(value);
if (duplicate == null) {
duplicate = new HashMap<>();
duplicates.put(value, duplicate);
}
duplicate.put(key, value);
});
System.out.println("Original: " + original);
duplicates.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
//
Original: {Player 1=Hello, Player 2=Hi, Player 3=Hi, Player 4=Hello, Player 5=Hello}
Hi: {Player 2=Hi, Player 3=Hi}
Hello: {Player 1=Hello, Player 4=Hello, Player 5=Hello}