fork download
  1. import java.util.Arrays;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Objects;
  7. import java.util.Set;
  8.  
  9. class Ideone {
  10. public static void main (String[] args) {
  11. ArrayList<Mobile> mobiles = new ArrayList<>();
  12. mobiles.add(
  13. Mobile.of(
  14. Plan.of("P1", "Plan 1"),
  15. Plan.of("P2", "Plan 2")));
  16. mobiles.add(Mobile.of(
  17. Plan.of("P1", "Plan 1"),
  18. Plan.of("P2", "Plan 2"),
  19. Plan.of("P3", "Plan 3"),
  20. Plan.of("P4", "Plan 4")));
  21. mobiles.add(Mobile.of(
  22. Plan.of("P1", "Plan 1"),
  23. Plan.of("P2", "Plan 2"),
  24. Plan.of("P5", "Plan 5"),
  25. Plan.of("P6", "Plan 6")));
  26. Set<Plan> commonPlans = extractCommonPlans(mobiles);
  27. System.out.println(commonPlans);
  28. }
  29.  
  30. public static Set<Plan> extractCommonPlans(List<Mobile> mobiles) {
  31. if (Objects.isNull(mobiles) || mobiles.isEmpty()) {
  32. return Collections.emptySet();
  33. }
  34.  
  35. HashSet<Plan> initialSet = new HashSet<>(mobiles.get(0).getPlans());
  36. return mobiles.stream()
  37. .map(Mobile::getPlans)
  38. .map(HashSet<Plan>::new)
  39. .reduce(initialSet, (plan1, plan2) -> {
  40. plan1.retainAll(plan2);
  41. return plan1;
  42. });
  43. }
  44. }
  45.  
  46. class Mobile {
  47. private final List<Plan> plans;
  48.  
  49. private Mobile(List<Plan> plans) {
  50. this.plans = plans;
  51. }
  52.  
  53. public static Mobile of(Plan... plans) {
  54. return new Mobile(Arrays.asList(plans));
  55. }
  56.  
  57. public List<Plan> getPlans() {
  58. return plans;
  59. }
  60. }
  61.  
  62. class Plan {
  63. private final String id;
  64. private final String name;
  65.  
  66. private Plan(String id, String name) {
  67. this.id = id;
  68. this.name = name;
  69. }
  70.  
  71. public static Plan of(String id, String name) {
  72. return new Plan(id, name);
  73. }
  74.  
  75. @Override
  76. public boolean equals(Object thatObject) {
  77. if (this == thatObject) {
  78. return true;
  79. }
  80. if (getClass() != thatObject.getClass()) {
  81. return false;
  82. }
  83. Plan that = (Plan) thatObject;
  84. return Objects.equals(id, that.id)
  85. && Objects.equals(name, that.name);
  86. }
  87.  
  88. @Override
  89. public int hashCode() {
  90. return Objects.hash(id, name);
  91. }
  92.  
  93. @Override
  94. public String toString() {
  95. return String.format("Plan{id=\"%s\", name=\"%s\"}", id, name);
  96. }
  97. }
Success #stdin #stdout 0.08s 34664KB
stdin
Standard input is empty
stdout
[Plan{id="P1", name="Plan 1"}, Plan{id="P2", name="Plan 2"}]