fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collection;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9.  
  10. public static void main(String[] args) {
  11.  
  12. Collection<Entity> first = new ArrayList<>(Arrays.asList(new Entity("id1", 1),
  13. new Entity("id1", 2), new Entity("id1", 3)));
  14.  
  15. Collection<Entity> second = new ArrayList<>(Arrays.asList(new Entity("id2", 3),
  16. new Entity("id2", 4), new Entity("id2", 5)));
  17.  
  18. first.forEach(entity -> {
  19. if (second.contains(entity)) {
  20. second.remove(entity);
  21. }
  22. });
  23. second.addAll(first);
  24. System.out.println(second);
  25. }
  26. }
  27.  
  28. class Entity {
  29.  
  30. String name;
  31. long id;
  32.  
  33. public Entity(String name, long id) {
  34. this.name = name;
  35. this.id = id;
  36. }
  37.  
  38. public Entity() {
  39. }
  40.  
  41. public long getId() {
  42. return id;
  43. }
  44.  
  45. public void setId(long id) {
  46. this.id = id;
  47. }
  48.  
  49. public String getName() {
  50. return name;
  51. }
  52.  
  53. public void setName(String name) {
  54. this.name = name;
  55. }
  56.  
  57. @Override
  58. public int hashCode() {
  59. int hash = 7;
  60. hash = 59 * hash + (int) (this.id ^ (this.id >>> 32));
  61. return hash;
  62. }
  63.  
  64. @Override
  65. public boolean equals(Object obj) {
  66. if (this == obj) {
  67. return true;
  68. }
  69. if (obj == null) {
  70. return false;
  71. }
  72. if (getClass() != obj.getClass()) {
  73. return false;
  74. }
  75. final Entity other = (Entity) obj;
  76. if (this.id != other.id) {
  77. return false;
  78. }
  79. return true;
  80. }
  81.  
  82. @Override
  83. public String toString() {
  84. return "Entity{" + "name=" + name + ", id=" + id + '}';
  85. }
  86.  
  87. }
  88.  
Success #stdin #stdout 0.14s 33332KB
stdin
Standard input is empty
stdout
[Entity{name=id2, id=4}, Entity{name=id2, id=5}, Entity{name=id1, id=1}, Entity{name=id1, id=2}, Entity{name=id1, id=3}]