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("id_1", 1),
  13. new Entity("id_1", 2), new Entity("id_1", 3)));
  14.  
  15. Collection<Entity> second = new ArrayList<>(Arrays.asList(new Entity("id_2", 3),
  16. new Entity("id_2", 4), new Entity("id_2", 5)));
  17.  
  18. second.forEach(entity -> first.removeIf(t -> t.getId() == entity.getId()));
  19. first.addAll(second);
  20.  
  21. System.out.println(first);
  22. }
  23. }
  24.  
  25. class Entity {
  26.  
  27. private String name;
  28. private long id;
  29.  
  30. public Entity(String name, long id) {
  31. this.name = name;
  32. this.id = id;
  33. }
  34.  
  35. public Entity() {
  36. }
  37.  
  38. public long getId() {
  39. return id;
  40. }
  41.  
  42. public void setId(long id) {
  43. this.id = id;
  44. }
  45.  
  46. public String getName() {
  47. return name;
  48. }
  49.  
  50. public void setName(String name) {
  51. this.name = name;
  52. }
  53.  
  54. @Override
  55. public String toString() {
  56. return "Entity{" + "name=" + name + ", id=" + id + '}';
  57. }
  58.  
  59. }
  60.  
Success #stdin #stdout 0.22s 33308KB
stdin
Standard input is empty
stdout
[Entity{name=id_1, id=1}, Entity{name=id_1, id=2}, Entity{name=id_2, id=3}, Entity{name=id_2, id=4}, Entity{name=id_2, id=5}]