lots of exercises in java... from https://github.com/exercism/java

CustomSet.java 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import java.util.Collection;
  2. import java.util.Collections;
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. import java.util.function.Predicate;
  6. import java.util.stream.Collectors;
  7. public class CustomSet<T> {
  8. private Set<T> set;
  9. public CustomSet() {
  10. this(Collections.emptyList());
  11. }
  12. public CustomSet(Collection<T> data) {
  13. set = new HashSet<>(data.size());
  14. this.set.addAll(data);
  15. }
  16. public boolean isEmpty() {
  17. return set.isEmpty();
  18. }
  19. public boolean contains(T element) {
  20. return set.contains(element);
  21. }
  22. public boolean isSubset(CustomSet<T> anotherSet) {
  23. return set.containsAll(anotherSet.set);
  24. }
  25. public boolean isDisjoint(CustomSet<T> anotherSet) {
  26. if (set.isEmpty() || anotherSet.set.isEmpty()) {
  27. return true;
  28. }
  29. return set.stream()
  30. .filter(elem -> anotherSet.set.contains(elem))
  31. .count() == 0;
  32. }
  33. public boolean equals(CustomSet<T> anotherSet) {
  34. return set.equals(anotherSet.set);
  35. }
  36. public boolean add(T element) {
  37. return set.add(element);
  38. }
  39. public CustomSet<T> getIntersection(CustomSet<T> anotherSet) {
  40. return new CustomSet<>(
  41. set.stream()
  42. .filter(anotherSet.set::contains)
  43. .collect(Collectors.toList())
  44. );
  45. }
  46. public CustomSet<T> getUnion(CustomSet<T> anotherSet) {
  47. final Set<T> union = new HashSet<>(set);
  48. union.addAll(anotherSet.set);
  49. return new CustomSet<>(union);
  50. }
  51. public CustomSet<T> getDifference(CustomSet<T> anotherSet) {
  52. final Predicate<T> predicate = anotherSet::contains;
  53. return new CustomSet<>(
  54. set.stream()
  55. .filter(predicate.negate())
  56. .collect(Collectors.toList())
  57. );
  58. }
  59. }